指令的理解-作用域范围

最近学习了一下angularjs的指令作用域scope的属性,掌握了指令 你就掌握了angularjs核心,一般我们在书写一个指令的时候,如果不写scope,默认的是指令和Controller之间可以互相访问通信,这个是最简单的,也是最危险的,因为虽然在编程上方便了,但是指令的 某些属性很容易被外部修改,因为指令一般是需要在多个地方复用的,所以为了保证写出可以高效封闭重复利用率高的指令必须要用到scope:

scope:false (指令的作用域继承父级作用域[parent]的,指令和Controller之间互相通信,可以随意传值更新)

scope:true(指令的作用域继承父级作用域[parent]的,同时创建了自己新的子作用域,并且指令和Controller之间不能互相通信)

scope:{ } (指令的作用域没有继承父级作用域,创建了自己的新作用域,如需与父级作用域通信,可以采取以下方式)

scope: {
          text: "@myText",
          myValue: "&myAttribute",
          twoWayBind: "=myTwoWayBind",
          oneWayBind: "&myOneWayBind"
       }

1. Text Binding

文本绑定用@引用,不管你传的什么值,他们总是被解析并返回字符串,也就是说什么变量值在{{}}里就返回什么值,比如:

<my-directive my-attribute="hello {{ userName }}" />

在controller里 赋值:

$scope.username = "Umur"

在指令作用域内,这个值将显示 “hello Umur” , 这个值会在每个周期更新.

 

2. One-way Binding

单向绑定是用前缀 & , 可以是任何类型。在指令范围内将被定义为getter函数,解释如下:

Controller:

 

/* more code */
$scope.someObject = { name:'Umur', id:1 };
/* more code */

  

HTML:

<my-directive my-attribute="someObject" />

  

Directive:

{
  scope: {myValue: "&myAttribute"},
  link: function (scope, iElm, iAttrs) {
    var x = scope.myValue();
    // x == {name:"Umur", id:1}
  }
}

因为他们是getter函数,所以是只读的,对他们做的任何修改都不能传播到父级作用域或更高的作用域。

3. Two-way Bindings

双向绑定用符号 "= "标记,这个才像真正意义上的绑定,对绑定值的任何修改将反映在任何作用域。 用例子说明如下:

Controller:

/* more code */
$scope.someObject = { name:'Umur', id:1 };
/* more code */

  

HTML:

<my-directive my-attribute="someObject" /> 

  

Directive:

{
  scope: {myValue: "=myAtrribute" },
  link: function (scope, iElm, iAttrs) {
    var x = scope.myValue.name;
    // x == "Umur";
    scope.myValue.name = "Kieslowski";
    // if we go to parent scope (controller's scope, in this example)
    // $scope.someObject.name == "Kieslowski";
    // would be true
  }
}

  

更详细的例子和说明请参考:https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/

 

原文地址:https://www.cnblogs.com/laneyfu/p/4825400.html