AngularJS指令详解(4)—指令中的绑定策略
2016-09-18 11:04
585 查看
在上一节中,我们知道了指令如何生成独立的scope,这一节中我们来仔细研究一下scope中的绑定策略。
总体来说scope的绑定策略分为3种:
(1)@ : 绑定字符串
(2)=: 与父控制器进行双向绑定
(3)&:用于调用父scope中的函数
1.基础方式
显示效果:
这是最基础的方法,实现了字符串在scope中的绑定
2.实际上,我们可以通过改写实现上述的方法
可以通过删除link函数,并且增加@绑定,这样就成功的实现指令中的属性与指令scope的字符串绑定。
3.‘=’绑定
如果使用=绑定,那么不仅可以改变指令中scope中值,同时也可以改变父控制器中的值,实现双向绑定。
例子:
效果就是,改变了指令中scope的值的同时也会改变控制器中相对应的变量的值,实现了控制器和指令中scope的双向绑定。效果如下:
3.‘&’方法
注意传递参数的方法。
总体来说scope的绑定策略分为3种:
(1)@ : 绑定字符串
(2)=: 与父控制器进行双向绑定
(3)&:用于调用父scope中的函数
1.基础方式
<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; } } });
显示效果:
这是最基础的方法,实现了字符串在scope中的绑定
2.实际上,我们可以通过改写实现上述的方法
app.directive('test',function(){ return{ restrict:'E', scope:{ word:'@' }, template:"<div>{{word}}</div>", } });
可以通过删除link函数,并且增加@绑定,这样就成功的实现指令中的属性与指令scope的字符串绑定。
3.‘=’绑定
如果使用=绑定,那么不仅可以改变指令中scope中值,同时也可以改变父控制器中的值,实现双向绑定。
例子:
<div> <span>ctrl:</span> <input ng-model="wordCtrl"/> </div> <test word="{{wordCtrl}}"></test> app.directive('test',function(){ return{ restrict:'E', scope:{ word:'@' }, template:"directive:<input ng-model='word' />", } });
效果就是,改变了指令中scope的值的同时也会改变控制器中相对应的变量的值,实现了控制器和指令中scope的双向绑定。效果如下:
3.‘&’方法
<test greet="sayHello()"></test> app.directive('test',function(){ return{ restrict:'E', scope:{ greet:'&' }, template:"<div ng-click='sayHello({name:'yuxiaoliang'})'>点击说HELLO</div>", } });
注意传递参数的方法。
相关文章推荐
- ionic list基础使用,适用于快速上手
- angular checkbox全选的双向绑定
- 万众瞩目之下,ANGULAR 2终于正式发布啦!
- 万众瞩目之下,ANGULAR 2终于正式发布啦!
- 万众瞩目之下,ANGULAR 2终于正式发布啦!
- AngularJS实现树形结构(ztree)菜单示例代码
- 利用AngularJS中ng-include实现静态HTML头文件和尾文件导入
- AngularJS指令详解(3)—指令与指令之间的交互
- angularjs中使用ng-bind-html和ng-include
- AngularJS指令详解(2)—指令与控制器之间的交互
- angularJS自定义指令(一)
- AngularJS内置指令之基础ng指令
- 搭建Ionic AngularJS Cordova开发环境
- AngularJs ng-change事件/指令
- AngularJS之指令
- angularjs中ng-show的使用
- AngularJS使用自定义指令替代ng-repeat的方法
- AngularJS中关于ng-class指令的几种实现方式详解
- AngularJS中过滤器的使用与自定义实例代码
- Angular定义服务-Learn By Doing