Andrew Allbright
Andrew Allbright

Reputation: 3839

How to interact with isolate scope variable within a directive controller?

I have directive myDirective, that has an two-way binding isolate scope. When the user clicks a button, I want to change the isolate scope to be a value. I thought isolate scopes were bound to the $scope, but I am wrong. How do I 'grab' and interact with that isolate scope? Are they not attached to the directive controller's scope?

angular.module("app", [])
.controller("myCtrl", function($scope){
    $scope.ctrlTwoway = "Eggs";
})
.directive("myDirective", function(){
    return {
        scope: {
          twoway: =
        },
        template: "<button ng-click="changeTwoway()">Change two way isolate scope</button>",
        controller: function($scope, $element, $attrs){
            $scope.changeTwoway = function(){
                // get twoway from isolate scope, and update the value with "bacon"
                // $scope.twoway = "bacon" doesn't work 
                // nor does $attrs.twoway = "bacon" work, either :(
            };
        }
    }
});

And the HTML

...
<div my-directive twoway="{{ctrlTwoway}}"></div>
Current value: {{ctrlTwoway}}

Upvotes: 5

Views: 11310

Answers (1)

Deividi Cavarzan
Deividi Cavarzan

Reputation: 10110

I created a plunker with working version.

You don't need to put {{variable}} on on the twoway="". Just change to twoway="ctrlTwoway" to work.

Another thing is that the way that you declare the binding. You are using = instead of '='.

Another thing is: try to use the link function instead of controller function in directives. It's a good practice and the right place if you want to manipulate DOM elements.

Source

I hope it helps.

Upvotes: 10

Related Questions