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

11,303

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.

Share:
11,303
Andrew Allbright
Author by

Andrew Allbright

Updated on June 13, 2022

Comments

  • Andrew Allbright
    Andrew Allbright about 2 years

    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}}
    
  • Andrew Allbright
    Andrew Allbright over 10 years
    That's the answer! Thanks