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}}
You just create a myVar variable in your controller and pass it to the directive using my-var attribute. Since you are using two way binding, any changes made to myVar by the directive are available in your controller. You can put a watch on myVar to track the changes. Show activity on this post.
Isolated scope directive is a scope that does not inherit from the parent and exist on its own. Scenario: Lets create a very simple directive which will show the object from the parent controller. var demoApp = angular.module('demoApp', []); demoApp.directive('myDirective', function() {
Scope in a Directive Well, all of the directives have a scope associated with them. This scope object is used for accessing the variables and functions defined in the AngularJS controllers, and the controller and link functions of the directive.
Isolate Scope: If the need is to reuse the component (directive) throughout your app, consider creating isolate scopes using scope option. The concept of isolate scope is used to separate the scope inside a directive from the scope outside.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With