Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
874 views
in Technique[技术] by (71.8m points)

angularjs directive : how to encapsulate css?

After a project with Web Components, i'm going back to AngularJS. I'm frustrated by the fact I can't find a proper way for a directive to keep its CSS internal (or encapsulated).

With web component I hadn't this problem since there is already a style tag that can be embedded in the template.

That's not the case with AngularJS directives.

Until here what I saw is :

1) define an CSS rule in an external file : my-directive {color:red;}, but this is not encapsulation.

2) define an internal rule with element.css({}); inside link function, but in this case the style is applied inline and thus is too heavy and cannot be easily override by external css.

Are there other ways ?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One Method you can try is declaring and assigning the styles in JavaScript.

Declare a Style object.

styles = {
        background: 'green',
        color: 'black'
      };

Assign the object to a template using ng-style

<div ng-style="$ctrl.styles">
   My Component with local CSS
</div>

Here are some the following advantages using this method

  1. Using Variables to drive themes.
  2. Mixins through merging two Style Objects together (lodashes _.defaults)
  3. Control over style overwriting.
  4. Applying styles through logical conditions.
  5. Having local Styles that can't effect other components.
  6. You can place styles in angular services and inject them into only the component that need them.

Full Example

//Component

class myComponent {
    constructor( myCSSService ) {
        this.styles = {
            background: 'black',
            color: 'white'
        };
        this.myCSSService = myCSSService;
    }
}

myComponent.$inject = [ 'myCSSService' ];

angular.module( 'myModule', [] )
    .component( 'myComponent', {
        controller: myComponent,
        bindings: {},
        template: `
          <div ng-style="$ctrl.styles">
            My Component with local CSS
          </div>
          <div ng-style="$ctrl.myCSSService.styles">
            My Component with Injected CSS
          </div>
        `,
    } );

//Style Service

class myCSSService{
  constructor( ) {
      this.styles = {
        background: 'green',
        color: 'black'
      };
  }
}

angular.module( 'myCSSModule', [] )
    .service( 'myCSSService', myCSSService );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...