[AngularJS] 理解AngularJS Directive中的Scope

默认情况下, AngluarJS不会为在一个Controller下的Directive创建一个单独的作用域(Scope). 这个Directive中的所有关于$scope的变量都是在它的Controller中定义, 并且会被其他的在同一Controller中的Directive所共享, 例如以下代码:

  <script>
    (function(angular) {
        angular.module('zzIsolateScopeTest', [])
            .directive("directiveOne", function () {
                return {
                    link : function($scope, $element, $attr) {
                        $scope.site = "腾讯";
                    }
                };
            })
            .directive("directiveTwo", function () {
                return {
                    link : function($scope, $element, $attr) {
                        $scope.site = "博客";
                    }
                };
            })
            .controller("mainController", function ($scope) {
                $scope.site = "百度";
            });
    })(window.angular);
  </script>
<div data-ng-controller="mainController">  
    <div class="row">
        <div class="col-md-3"><a data-directive-one class="btn btn-default btn-block">{{site}}</a></div>
    </div>
    <div class="row">
        <div class="col-md-3"><a data-directive-two class="btn btn-default btn-block">{{site}}</a></div>
    </div>
</div>

打开页面的结果是两个"博客"链接的按钮. 这是因为DirectiveTwo在最后将site的值修改为了"博客", 并且影响到了DirectiveOne原来所修改成的值"腾讯".


AngluarJS引入isloate scope的概念, 使得每个Directive都能拥有自己的$scope变量, 从而不会在多个Directive之间因共享变量而造成数据错误. 使用isolate scope的方法很简单, 只需要在Directive的代码中写入一个属性即可:

scope : {}

示例代码如下:

  <script>
    (function(angular) {
        angular.module('zzIsolateScopeTest', [])
            .directive("directiveOne", function () {
                return {
                    scope : {},
                    link : function($scope, $element, $attr) {
                        $scope.site = "腾讯";
                    }
                };
            })
            .directive("directiveTwo", function () {
                return {
                    scope : {},
                    link : function($scope, $element, $attr) {
                        $scope.site = "博客";
                    }
                };
            })
            .controller("mainController", function ($scope) {
                $scope.site = "百度";
            });
    })(window.angular);
  </script>

通过这样的方式, directive-one和directive-two都拥有了自己的$scope, 也就是说, 它们将不再使用mainController中的$scope. 那么做这样的修改之后, 页面将会出现什么结果呢?

答案是页面上出现两个"百度"链接按钮.

如上面所说的, 当directive拥有自己的$scope之后, 将不会影响mainController中的$scope, 所以, 这里的两个占位符自然就mainController中的site值来填充. 也就是"百度".

 

转载于:https://www.cnblogs.com/AmusementPark/p/4293006.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值