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; }

alexandernst
  • 14,352
  • 22
  • 97
  • 197
  • 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"_? – a better oliver Mar 14 '16 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. – alexandernst Mar 14 '16 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. – a better oliver Mar 14 '16 at 13:10
  • @zeroflagL the `.directive` function will run once for each directive coincidence in the HTML code, right? (two `` 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. – alexandernst Mar 14 '16 at 13:12
  • 1
    The directive function runs exactly once. The compile, link etc. functions run once per element. – a better oliver Mar 14 '16 at 13:17
  • I am confused. I always lived under the assumption that `run()` and `config()` blocks were a feature of angular modules and not applicable to directives? – Johannes Jander Mar 14 '16 at 13:18

1 Answers1

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;
}
Starscream1984
  • 3,072
  • 1
  • 19
  • 27
  • 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) – alexandernst Mar 14 '16 at 13:23
  • 1
    There's a few techniques in the answers to this question: http://stackoverflow.com/questions/324486/how-do-you-read-css-rule-values-with-javascript – Starscream1984 Mar 14 '16 at 13:33