Isolate Scope - Element Access Scope Attributes

When creating a scoped directive, I cannot access the scoped properties on the directive element (this was not the case in angular 1.0.7, but in more recent 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 the property scopes of the directive element itself, not just their parent elements in angular 1.0.7+?

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

+3


source to share


2 answers


Since you tried to isolate 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 tries to use the parent "isRed" scope, and your directive actually sets the "isRed" child scope.

As an alternative to the above

initialize an object:



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

      

use a directive like this:

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

      

see ngClass "=":

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

      

+1


source


It works if you replace the scope.isRed with a function instead of just setting it to true.

scope.isRed = function() {
 return true;
}

      



I'm not sure why this has changed since an earlier version of Angular, but it makes sense to use a function rather than a direct assignment.

0


source







All Articles