0

I have a directive and I want to inject some CSS for that directive.

As there could be multiple directives in the same page, I want to avoid injecting that CSS multiple times. What method should I use? .run? .config?

Also, how exactly would I inject that CSS?

For the sake of this example, let's say that I just want to inject .my-item { background: blue; }

6
  • Is it possible that you confuse directives with elements (directive = JavaScript, element = HTML)? What exactly do you mean by "inject some CSS for that directive"? Commented Mar 14, 2016 at 12:51
  • @zeroflagL "directive" == angular directive. "Inject some CSS for that directive" == Some CSS styling generated with javascript, instead of fetching a .css file. Commented Mar 14, 2016 at 12:52
  • The place to inject CSS is the directive function. It only depends on your code if CSS is injected multiple times or not. Commented Mar 14, 2016 at 13:10
  • @zeroflagL the .directive function will run once for each directive coincidence in the HTML code, right? (two <my-directive></my-directive> elements will trigger the .directive function twice). What I'm asking is if .run or .config will be ran once, thus allowing me to avoid checking if the styles were already injected. Commented Mar 14, 2016 at 13:12
  • 1
    The directive function runs exactly once. The compile, link etc. functions run once per element. Commented Mar 14, 2016 at 13:17

1 Answer 1

1

You can add some generated CSS in angular by doing the following:

angular.element(document).find('head').prepend('<style type="text/css">.my-item { background: blue; }</style>');

To make sure that this isn't injected multiple times, you could create a service CssSvc which can keep track of whether the generated CSS has been injected yet or not.

app.service('CssSvc', function () {
    var svc = this;

    // keep track if injected
    svc.injected = false;

});

Then you can inject the service in to your directive and only run the above code if it has not been run already.

if(!CssSvc.injected) {
    angular.element(document).find('head').prepend('<style type="text/css">.my-item { background: blue; }</style>');
    CssSvc.injected = true;
}
Sign up to request clarification or add additional context in comments.

2 Comments

One more thing. Is there a way I can fetch the definition of a css class? (Not by searching for an item in the DOM that has been assigned that class, but the class itself)
There's a few techniques in the answers to this question: stackoverflow.com/questions/324486/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.