Rumah  >  Artikel  >  hujung hadapan web  >  AngularJS指令中的绑定策略实例分析

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

高洛峰
高洛峰asal
2016-12-24 09:51:25987semak imbas

本文实例讲述了AngularJS指令中的绑定策略。分享给大家供大家参考,具体如下:

在前面的文章中,我们知道了指令如何生成独立的scope,这一节中我们来仔细研究一下scope中的绑定策略。

总体来说scope的绑定策略分为3种:

(1)@ : 绑定字符串

(2)=: 与父控制器进行双向绑定

(3)&:用于调用父scope中的函数

1.基础方式

<test word="{{wordCtrl}}"></test>

   

app.controller(&#39;myController1&#39;,[&#39;$scope&#39;,function($scope){
    $scope.wordCtrl="hello";
}]);
app.directive(&#39;test&#39;,function(){
    return{
     restrict:&#39;E&#39;,
     template:"<div>{{word}}</div>",
     link:function(scope,ele,attr){
      scope.word=attr.word;
     }
    }
});

显示效果:

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

这是最基础的方法,实现了字符串在scope中的绑定

2.实际上,我们可以通过改写实现上述的方法

app.directive(&#39;test&#39;,function(){
    return{
     restrict:&#39;E&#39;,
     scope:{
      word:&#39;@&#39;
     },
     template:"<div>{{word}}</div>",
    }
});

   

可以通过删除link函数,并且增加@绑定,这样就成功的实现指令中的属性与指令scope的字符串绑定。

3.‘='绑定

如果使用=绑定,那么不仅可以改变指令中scope中值,同时也可以改变父控制器中的值,实现双向绑定。

例子:

ctrl:
<test word="{{wordCtrl}}"></test>

   

app.directive(&#39;test&#39;,function(){
    return{
     restrict:&#39;E&#39;,
     scope:{
      word:&#39;@&#39;
     },
     template:"directive:<input ng-model=&#39;word&#39; />",
    }
});

   


效果就是,改变了指令中scope的值的同时也会改变控制器中相对应的变量的值,实现了控制器和指令中scope的双向绑定。

效果如下:

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

3.‘&'方法

<test greet="sayHello()"></test>


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

注意传递参数的方法。

希望本文所述对大家AngularJS程序设计有所帮助。

更多AngularJS指令中的绑定策略实例分析相关文章请关注PHP中文网!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn