Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isolate scope - access scope attributes on element

When creating a directive with isolate scope, I can't access scope properties on the directive element (it's was not the case in angular 1.0.7, but in later versions (e.g. 1.2.17)).

angular.module("app", []).directive("red", function() {
  return {
    scope: {},
    link: function(scope) {
      scope.isRed = true;
    }
  };
});

.red {
  color: #ff0000;
}

<div red ng-class="{red: isRed}">This is red in angular 1.0.7</div>

<div red ng-class="{red: isRed}">This is NOT red in angular 1.2.17</div>

See demo.

So, is there a way to access scope properties on the directive element itself, not just on their parent elements in angular 1.0.7+?

I know I can use some workarounds, but what would be a "clear" solution to this?

like image 832
Tamás Pap Avatar asked Jun 11 '26 07:06

Tamás Pap


1 Answers

Because you tried to isolate the scope, try:

angular.module("app", []).directive("foo", function() {
  return {
    scope: {},
    transclude: true,
    template: "<div ng-class='{red: isRed}'><ng-transclude/></div>",
    link: function(scope,element) {
      scope.isRed = true;

    }
  };
});

Your code is trying to use the parent's scope's "isRed", and your directive is actually setting a child scope's "isRed".

As an alternative to the above

initialize an object:

<div ng-init="color={red:true}"></div>  

use the directive like so:

<div foo ng-class="color">Hello world</div>

see the ngClass "=":

angular.module("app", []).directive("foo", function() {
  return {
    scope: {
      ngClass: "="
    },
    link: function(scope,element) {
      scope.ngClass.red = true;
    }
  };
});
like image 178
Noypi Gilas Avatar answered Jun 13 '26 00:06

Noypi Gilas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!