《AngularJS》--指令的相互调用

       人们喜欢AngularJS,因为他很有特色,其中他的指令和双向数据绑定很吸引着人们,那么,AngularJS的指令有什么作用哪?指令之间的是怎样相互调用的哪?

       下面有一个小小的Demo,写的是AngularJS指令之间的相互调用,大家看一下。这个Demo是这样的,页面上有三个div,每个div绑定不同的指令,当我们用鼠标滑过三个div时以触发不同的事件。

       HTML代码

<!DOCTYPE html>
<html lang="en" ng-app="MyModule">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div class="row">
    <div class="col-md-3">
        <superman strength> 动感超人 力量</superman>
    </div>
    </div>

    <div class="row">
        <div class="col-md-3">
            <superman strength speed> 动感超人 力量 速度 </superman>
        </div>
    </div>

    <div class="row">
        <div class="col-md-3">
            <superman strength speed light> 动感超人 力量 速度 发光</superman>
        </div>
    </div>
</body>
<script src="angular-1.3.0.14/angular.js"></script>
<script src="superman.js"></script>
</html>
      JS代码
var myModule=angular.module("MyModule",[]);

myModule.directive("superman",function(){
    return{
        scope:{},
        restrict:'AE',
        controller:function($scope){
            $scope.abilities=[];
            this.addStrength=function(){
                $scope.abilities.push("strength");
            };
            this.addSpeed=function(){
                $scope.abilities.push("speed");
            };
            this.addLight=function(){
                $scope.abilities.push("light");
            };
        },
        link:function(scope,element,attrs){
            element.addClass('btn btn-primary');
            element.bind("mouseenter",function(){
               alert(scope.abilities);
            })
        }
    }


});

myModule.directive("strength",function(){
    return{
        require:'^superman',
        link: function (scope, element, attrs, supermanCtrl) {
            supermanCtrl.addStrength();
        }
    }
});

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

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

      在上面的HTML标签中,我们看见了在每个div中,都有自定义的标签,像<superman>、<speed>、<light>等等, 我们可以给这些标签绑定特殊的一些功能,我们需要每个标签绑定的功能不一样,这时候,我们就用到ng-Controller和directive了,其中superman指令中的Controller里面定义了很多方法,这些方法就能提供给外面的一些指令使用,这样就能形成指令的嵌套使用。

     

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 19
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值