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

来源:互联网 发布:东德歧视中国人知乎 编辑:程序博客网 时间:2024/05/29 19:43

       人们喜欢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 0
原创粉丝点击