关于angularjs的指令中的scope

html文件:

<!doctype html>
<html ng-app="app">
    <head>
    </head>
    <body>

        <div>
            <superman strengh>strengh</superman><br>
            <superman strengh speed>strengh and speed</superman><br>
            <superman strengh speed light>strengh and speed and light</superman><br>
        </div>
        <script src="angular.min.js"></script>
        <script src="js/aa.js"></script>
    </body>
</html>

aa.js文件:

/**
*  Module
*
* Description
*/
var app = angular.module('app', []);

app.directive("superman", function(){
    return {
        restrict: "AE",
        scope:{

        },
        controller: function($scope) {
            $scope.abilities = [];
            this.addStrengh = function () {
                $scope.abilities.push("strengh");
            };
            this.addSpeed = function () {
                $scope.abilities.push("speed");
            };
            this.addLight = function () {
                $scope.abilities.push("light");
            }
        },
        link: function(scope, element, attrs) {
            element.bind("mouseenter", function(event){
                // scope.loadData();
                // scope.$apply("loadData()");
                // scope.$apply(attrs.howtoload);
                console.log(scope.abilities);
            })
            
        }

    }
});

app.directive("strengh", function(){
    return {
        require: "^superman",
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addStrengh();
        }

    }
});
app.directive("speed", function(){
    return {
        require: "^superman",
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addSpeed();
        }

    }
});
app.directive("light", function(){
    return {
        require: "^superman",
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addLight();
        }

    }
});

三个指令继承过来之后,就形成了自己的scope。

子指令没有定义scope,在link中的scope是从父scope(这里的父scope应该是 rootScope)传进来的,所以如果用link的scope直接去调用方法是报错的。因为继承的指令superman有自己的scope,这个scope应该是独立的、和rootScope没关系,总之是引用不到的。

总结:这里的link的scope参数是父scope(rootScope)传进来的,通过superman继承new一个自己独立的scope


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值