Angular学习心得——directive的bindToController选项

      the component's properties are bound to the controller rather than to the scope.html

      we can move all our property binding definitions to bindToController and make it an object literalangularjs

     这两段话引用自Pascal Precht在thoughtram blog上的一篇文章(连接:http://blog.thoughtram.io/angularjsdom

/2015/01/02/exploring-angular-1.3-bindToController.html)函数

      意思是,当使用了bindToController选项后,组件的属性会被绑定到controller上,而不是scope上,而且咱们能够把本来定义在scope中的属性绑定都迁移到bindToController选项中来,并成为对象字面量的形式ui

      意即,本来像以下形式的绑定策略:this

      

scope:{
   name:'=',
   age:'='
}


    更改成以下的形式:spa

bindToController:{
   name:'=',
   age:'='
}

  接着,咱们须要controller和controllerAs的帮忙,对controller进行实例化:.net

bindToController:{
   name:'=',
   age:'='
},
controller: function(){
  var vm = this
},
controllerAs: 'ctrl'

此时,controller已经做为对象字面量的形式而存在了,ctrl是它的实例,
因而,咱们能够在template中,以ctrl.XXXX的形式来调用被绑定到controller上的组件属性

这里附上具体的demo:code

https://jsfiddle.net/lee1994522/rvu0xqut/4/ component

但若是须要在link函数的dom操做中用到这些绑定的属性,该怎么办呢?按照原来的作法,咱们固然是使用scope.xxxx的形式来调用这些属性,但如今咱们不用scope了,因此,咱们要借助require选项,以下:

require:'这里是指令的名称'

接着,在link函数传入第四个参数ctrl,咱们就能够使用这些属性了,再附上demo:

https://jsfiddle.net/lee1994522/up8mqwy7/

以上是我对bindToController的浅薄认识,恳请各位大神指出不足之处,谢谢

相关文章
相关标签/搜索