CSS in angular directive

I am writing an Angular directive to display some information about a music album, it currently displays information below the album cover, but if the item becomes too small, it should compress the album cover and put the following information to it. At the moment, I only have html on the page and I have css to make changes on the main page, but this leads to the page being pretty monolithic as it also displays other things, so I want to separate it from the directive.

However, I don’t see how to include CSS in the directive, I don’t want to include it in the string in html, and I could put the style tag in html and put it there, but then it will be repeated every time I use the directive. Is there a way to insert a link into a CSS file in the head from a directive? For example, there is a templateUrl field, are there stylesheetUrl or something else?

+4
source share
3 answers

You can check this module: angular-css-injector .
Be warned that it is currently only compatible with angular 1.2.x ...

+1
source

You can enter css in your directive as follows:

var head = document.getElementsByTagName('head')[0];
var cs = document.createElement('link');
cs.rel = 'stylesheet';
cs.href = 'css/myStylesheet.css';
head.appendChild(cs);

So, the directive will look like this:

app.directive('myDirective', function () {
    var head = document.getElementsByTagName('head')[0];
    var cs = document.createElement('link');
    cs.rel = 'stylesheet';
    cs.href = 'css/myStylesheet.css';
    head.appendChild(cs);
    return {
        templateUrl:'templates/myTemplate.html',
        link: function (scope, elm, attrs, ctrl) {

        }
    };
});
0

angular angular. angular , ( ) html, css javascript , , .

( ), , ( gulp) CSS ( , Stylus).

:

  • angular ( ) my-albums.coffee:

    angular.module('my-albums', [])
    
    .directive('myAlbumDirective', ()->
      restrict: 'A'
      templateUrl: 'SomeTemplate.jade'
      # etc.
    )
    
  • my-album-directive.jade

    .album
      img(ng-src="{{album.imageUrl}})
      span.name {{album.name}}
    
  • , : _my-albums.styl. css.

    [myAlbumDirective]
      .album
        display flex
        flex-direction column
        @media screen and (min-width: 600px)
          flex-direction row
    

, angular app.coffee ( ), main.styl:

@import '../my-albums/_my-albums.styl'

, ( ):

  • .jade app.templates angular ( $templateCache (app.templates app.coffee
  • coffeescript script.js
  • , style.css

:

script(src='js/app.js')
link(rel='stylesheet', href='css/style.css')

TL; DR:

, angular, -, .

Note Soon TM will be fine (see web components and angular 2.0 )

0
source

All Articles