The examples in this article describe the binding strategy in AngularJS directives. Share it with everyone for your reference, the details are as follows:
In the previous article, we know how the instruction generates an independent scope. In this section, we will take a closer look at the binding strategy in the scope.
In general, scope binding strategies are divided into 3 types:
(1)@: binding string
(2)=: two-way binding with the parent controller
(3)&: used Call the function in the parent scope
1. Basic method
app.controller('myController1',['$scope',function($scope){ $scope.wordCtrl="hello"; }]); app.directive('test',function(){ return{ restrict:'E', template:"{{word}}", link:function(scope,ele,attr){ scope.word=attr.word; } } });
Display effect:
This is the most basic method, which realizes the binding of strings in the scope
2. In fact, We can implement the above method by rewriting
app.directive('test',function(){ return{ restrict:'E', scope:{ word:'@' }, template:"{{word}}", } });
By deleting the link function and adding @binding, we can successfully achieve string binding between the attributes in the instruction and the instruction scope.
3. ‘=’ binding
If you use = binding, you can not only change the value in the scope of the instruction, but also change the value in the parent controller to achieve two-way binding.
Example:
ctrl:
app.directive('test',function(){ return{ restrict:'E', scope:{ word:'@' }, template:"directive:", } });
The effect is that when changing the value of the scope in the instruction, it will also change the value of the corresponding variable in the controller, realizing the two-way connection between the controller and the scope in the instruction. Binding.
The effect is as follows:
3. ‘&’ method
app.directive('test',function(){ return{ restrict:'E', scope:{ greet:'&' }, template:"点击说HELLO", } });
Pay attention to the method of passing parameters.
I hope this article will be helpful to everyone in AngularJS programming.
For more related articles on the analysis of binding strategy examples in AngularJS instructions, please pay attention to the PHP Chinese website!