angular directives scope

以前学过,但是忘记了,所以重新记录一篇文章。

directive中的restrict属性,来决定这个指令是作为标签(E)、属性(A)、属性值(C)、还是注释(M)。

1、false(默认值):直接使用父scope。比较“危险”。

可以理解成指令内部并没有一个新的scope,它和指令以外的代码共享同一个scope。

2、true:继承父scope

 

 

3、{ }:创建一个新的“隔离”scope,但仍可与父scope通信

隔离的scope,通常用于创建可复用的指令,也就是它不用管父scope中的model。然而虽然说是“隔离”,但通常我们还是需要让这个子scope跟父scope中的变量进行绑定。绑定的策略有3种:

  • @:单向绑定,外部scope能够影响内部scope,但反过来不成立
  • =:双向绑定,外部scope和内部scope的model能够相互改变
  • &:把内部scope的函数的返回值和外部scope的任何属性绑定起来
(1)@:单向绑定

示例代码:

<body ng-app="watchDemo">
<!--外部scope-->
<p>父scope:<input type="text" ng-model="input"></p>
<!--内部隔离scope-->
<my-directive my-text="{{input}}"></my-directive>

<script>
    var app = angular.module('watchDemo', []);
    app.directive('myDirective', function () {
        return {
            restrict: 'E',
            replace: true,
            template: '<p>自定义指令scope:<input type="text" ng-model="myText"></p>',
            scope: {
                myText: '@'
            }
        }
    });
</script>
</body>

(2)=:双向绑定

示例代码:

<body ng-app="watchDemo">
<!--外部scope-->
<p>父scope:<input type="text" ng-model="input"></p>

<!--内部隔离scope-->
<!--注意这里,因为是双向绑定,所以这里不要“{{}}”这个符号-->
<my-directive my-text="input"></my-directive>

<script>
    var app = angular.module('watchDemo', []);
    app.directive('myDirective', function () {
        return {
            restrict: 'E',
            replace: true,
            template: '<p>自定义指令scope:<input type="text" ng-model="myText"></p>',
            scope: {
                myText: '=' // 这里改成了双向绑定
            }
        }
    });
</script>
</body>
(3)&:内部scope的函数返回值和外部scope绑定

 

<body ng-app="watchDemo">
<!--外部scope-->
<p>父scope:<input type="text" ng-model="input"></p>

<!--内部隔离scope-->
<!--注意这里,函数名字也要用 连字符命名法-->
<my-directive get-my-text="input"></my-directive>

<script>
    var app = angular.module('watchDemo', []);
    app.directive('myDirective', function () {
        return {
            restrict: 'E',
            replace: true,
            template: '<p>结果:{{ getMyText() }}</p>',
            scope: {
                getMyText: '&' // 这里改成了函数返回值的绑定
            }
        }
    });
</script>
</body>

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |