Bind variable inside angularjs directive isolated scope
Every AngularJs developer knows about AngularJs directives.Knows how cool it is,but now many developer know about isolated scope methods.In general AngularJs directive scope has 3 types: inherit,not inherit and isolated.Today We will talk about isolated scope.
Since AngularJS is now a deprecated framework, you can use JavaScript modern frameworks like Vuejs, React and Angular, instead.
Using isolated scope for directives,you will have 3 ways to use: '=', '@', '&'.The first one is 2 ways binding.
Sometimes you want to have directive with isolated scope,but you need bind it anywhere.For example you want to set listener on it (watch).There are 2 ways to do it.Lets see it.
...
module.directive("myDirective",function(){
return {
...
link: function(scope, el, attrs){
scope.$watch(attrs.[any_attribute],function(data){ // for example any_attribute = 'ngModel'
// anything you want
},true)
}
}
})
...
module.directive("myDirective",function(){
return {
...
scope: {
variable: '='
}
...
link: function(scope, ...){
scope.$watch('variable',function(data){
// anything you want
},true)
}
}
})
As you see, there are 2 ways to do it, but the Second way is more professional.