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
<test word="{{wordCtrl}}"></test>
app.controller('myController1',['$scope',function($scope){ $scope.wordCtrl="hello"; }]); app.directive('test',function(){ return{ restrict:'E', template:"<div>{{word}}</div>", 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:"<div>{{word}}</div>", } });
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:<test word="{{wordCtrl}}"></test>
app.directive('test',function(){ return{ restrict:'E', scope:{ word:'@' }, template:"directive:<input ng-model='word' />", } });
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
<test greet="sayHello()"></test>
app.directive('test',function(){ return{ restrict:'E', scope:{ greet:'&' }, template:"<div ng-click='sayHello({name:'yuxiaoliang'})'>点击说HELLO</div>", } });
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!