最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I use AngularJs Directives to apply a style to a pseudo Element - Stack Overflow

programmeradmin1浏览0评论

I hope I'm not missing something obvious here but I am trying to learn Angular and I have run in to a problem whilst trying to make a directive.

I am trying to build a Directive that will take the url from a data-attribute ('background-image') and apply that as a background-image to a pseudo element, but I am having trouble figuring out how to target the ::before element or even if Angular can modify a pseudo element.

Here is the directive I am trying to build:

I can get it to apply the background to div.item but when I try target the ::before no joy.

Here is the directive code:

angular.module('testApp', [
])

angular.module('testApp')
  .directive('backgroundImage', function(){
    return function(scope, element, attrs){
        restrict: 'A',
        attrs.$observe('backgroundImage', function(value) {
      // If I remove ::before it will apply image background to .item correctly.
        element::before.css({
                'background-image': 'url(' + value +')'
            });
        });
    };
});

I hope I'm not missing something obvious here but I am trying to learn Angular and I have run in to a problem whilst trying to make a directive.

I am trying to build a Directive that will take the url from a data-attribute ('background-image') and apply that as a background-image to a pseudo element, but I am having trouble figuring out how to target the ::before element or even if Angular can modify a pseudo element.

Here is the directive I am trying to build: http://cdpn.io/cqvGH

I can get it to apply the background to div.item but when I try target the ::before no joy.

Here is the directive code:

angular.module('testApp', [
])

angular.module('testApp')
  .directive('backgroundImage', function(){
    return function(scope, element, attrs){
        restrict: 'A',
        attrs.$observe('backgroundImage', function(value) {
      // If I remove ::before it will apply image background to .item correctly.
        element::before.css({
                'background-image': 'url(' + value +')'
            });
        });
    };
});
Share Improve this question asked Apr 25, 2014 at 12:21 DaimzDaimz 3,28114 gold badges51 silver badges77 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

It is tricky , but possible. Try something like:

 var style = "<style>.item:before{background-image:url("+value+")}</style>"
 angular.element("head").append(style);

Working here: http://codepen.io/anon/pen/Difrt

发布评论

评论列表(0)

  1. 暂无评论