源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

AngularJS指令中的绑定策略实例分析

  • 时间:2021-08-02 17:25 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:AngularJS指令中的绑定策略实例分析
本文实例讲述了AngularJS指令中的绑定策略。分享给大家供大家参考,具体如下: 在前面的文章中,我们知道了指令如何生成独立的scope,这一节中我们来仔细研究一下scope中的绑定策略。 [b]总体来说scope的绑定策略分为3种:[/b] (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;
     }
    }
});

显示效果: [img]http://files.jb51.net/file_images/article/201612/20161214111213062.png?20161114111243[/img] 这是最基础的方法,实现了字符串在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的双向绑定。 效果如下: [img]http://files.jb51.net/file_images/article/201612/20161214111250252.png?20161114111312[/img] 3.‘&'方法
<test greet="sayHello()"></test>

app.directive('test',function(){
    return{
     restrict:'E',
     scope:{
      greet:'&'
     },
     template:"<div ng-click='sayHello({name:'yuxiaoliang'})'>点击说HELLO</div>",
    }
});

注意传递参数的方法。 更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/893.htm]AngularJS入门与进阶教程[/url]》及《[url=http://www.1sucai.cn/Special/898.htm]AngularJS MVC架构总结[/url]》 希望本文所述对大家AngularJS程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部