Tamás Pap
Tamás Pap

Reputation: 18273

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?

Upvotes: 3

Views: 87

Answers (2)

noypi
noypi

Reputation: 991

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

Upvotes: 1

Carl
Carl

Reputation: 1258

It works if you replace the scope.isRed with a function rather than just setting the value of true.

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

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

Upvotes: 0

Related Questions