Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use AngularJs Directives to apply a style to a pseudo Element

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 +')'
            });
        });
    };
});
like image 706
Daimz Avatar asked Apr 25 '14 12:04

Daimz


People also ask

What are AngularJS directives used for?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

Which directive is used to assign values to the variables in AngularJS?

ng-init directive It is used to declare and assign values to the variables for an AngularJS application.

Which type of case do we use for naming a custom directive in AngularJS?

AngularJS normalizes an element's tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel ).

What is custom directive in AngularJS?

What is Custom Directive? A Custom Directive in AngularJS is a user-defined directive that provides users to use desired functions to extend HTML functionality. It can be defined by using the “directive” function, and it replaces the element for which it is used.


1 Answers

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

like image 110
Ivan Chernykh Avatar answered Sep 30 '22 02:09

Ivan Chernykh