Lucas Raines
Lucas Raines

Reputation: 1315

AngularJS: Directive not getting controller's variable from scope

I have an element that has both a controller and a directive with an isolate scope applied to it:

scope: {
    dirVar: '='
}

The goal is to run certain parts of the directive only if a variable holds true. I'm setting that variable in the controller and trying to pass it into the directive through an attr.

The problem is that when I do something like

<div ng-controller="MyCtrl" my-directive active="ctrlVar"></div>

and try to get active in the directive with scope.active, it always comes up undefined.

Here is an example: http://jsfiddle.net/u3t2u/1/

Any explanation as to why or how to properly do this? I assume the problem is with the controller and directive being applied to the same element and wish to get around that.

Another option would be to remove the directive's isolate scope and have it evaluate an attr passed to it, but I'm not sure how to do that ($parse keeps throwing errors).

Upvotes: 1

Views: 2858

Answers (3)

Lucas Raines
Lucas Raines

Reputation: 1315

Ended up changing the way I structured the directive because it wasn't something that should really have had an isolate scope, and the only reason it did was so it could take expressions and evaluate them to true or false.

So I changed it to use $parse, which left the directive looking something like:

var active = $parse(attrs.isActive);

// Evaluate contents of attrs.isActive
// as if they are variables within its scope,
// which is inherited from parent scopes
if(active(scope)) {
    // do something
}

Upvotes: 1

yanhan
yanhan

Reputation: 3537

I am not too familiar with certain things like transclude and creating an isolated scope, but this is what I got after reading the docs for Directives and fiddling around:

http://jsfiddle.net/u3t2u/4/

I only changed this portion of the html:

<div ng-controller="MyCtrl">
    <div my-directive active="myValue">
    Testing.
    </div>
</div>

I believe that in this case, you do not actually have to pass a value to the my-directive directive, since you are already using an isolate scope with an =. Sorry if my explanation is not that good. You can read more at http://docs.angularjs.org/guide/directive , under the section Writing directives (long version).

Upvotes: 0

Brian Lewis
Brian Lewis

Reputation: 5729

That is because your directive is not inside the controller. Try this:

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
        <div my-directive="" active="myValue">
             Testing.
        </div>
    </div>
</div>

Upvotes: 1

Related Questions