Bind variable inside angularjs directive isolated scope
AngularJS is a JavaScript-based open-source front-end web framework. Read information about the isolated scope methods and the types of AngularJs directive scope. Also, see examples of how to do it.
Every AngularJS developer knows about AngularJS directives and how powerful they are, but not many developers are familiar with isolated scope methods. In general, AngularJS directive scopes have two main types: inherited (default) and isolated. Today, we will talk about isolated scope.
Using isolated scope for directives, you have three binding types: =, @, and &. The = binding is used for two-way data binding.
Sometimes you want a directive with an isolated scope but still need to watch a bound variable. For example, you might want to set up a listener using $watch or $attrs.$observe. There are two common ways to do this. Let's look at them.
Example 1
module.directive("myDirective", function() {
return {
// ... (other directive properties)
link: function(scope, el, attrs) {
attrs.$observe('any_attribute', function(data) { // for example any_attribute = 'ngModel'
// anything you want
});
}
};
});Example 2
module.directive("myDirective", function() {
return {
// ... (other directive properties)
scope: {
variable: '='
},
link: function(scope, ... ) {
scope.$watch('variable', function(data) {
// anything you want
}, true);
}
};
});As you can see, there are two ways to do this, but the second approach is generally preferred for two-way data bindings. Use $attrs.$observe when watching attribute strings (like @ bindings), and scope.$watch when watching bound scope variables (like = bindings).
Binding Types Overview
@(One-way binding): Passes a string value from the parent scope to the isolated scope. Useful for static attributes.=(Two-way binding): Creates a two-way data binding between the parent scope and the isolated scope.&(Expression binding): Allows the directive to execute a function in the parent scope.
HTML Usage Example
<my-directive variable="parentVar" attr-value="staticText" on-change="handleEvent()"></my-directive>