背景介绍
这例子是视频中的例子,有一个动感超人,有三种能力,力量strength,速度speed,发光light。
这三种能力作为三种属性,定义动感超人作为一个标签,只要添加对应的属性就能拥有该能力。
为了便于结果的展示,为标签添加鼠标的响应事件,当鼠标移动到对应的标签上就会触发一个方法,打印出具备的能力。
程序分析
html部分的代码如下:
<div> <superman>nothing!</superman> <superman strength >strength!</superman> <superman strength speed >strength speed!</superman> <superman strength speed light >strength speed light!</superman> </div>
下面看看如何实现,首先依然是创建一个模块:
var myAppModule = angular.module("myApp",[]);
在该模块的基础上,创建标签superman,与前面类似。
myAppModule.directive("superman",function(){ return{ scope:{}, restrict:'AE', transclude:true, template:"<div><div ng-transclude></div></div>", 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,attr){ element.bind("mouseenter",function(){ console.log(scope.abilities); }); } } });
这里不同的是,在方法内部有一个controller属性,这个并不是ng-controller这种控制器,而是指令对外开放的一个接口,里面声明的方法,在外部可以作为公开的方法使用,其他的指令可以通过依赖,使用这些方法。
接下来再创建三个能力对应的指令
myAppModule.directive("strength",function(){ return{ require:'^superman', link:function(scope,element,attr,supermanCtrl){ supermanCtrl.addStrength(); } } }); myAppModule.directive("speed",function(){ return{ require:'^superman', link:function(scope,element,attr,supermanCtrl){ supermanCtrl.addSpeed(); } } }); myAppModule.directive("light",function(){ return{ require:'^superman', link:function(scope,element,attr,supermanCtrl){ supermanCtrl.addLight(); } } });
三个指令的代码都差不多,其中require指定了依赖的指令。
link中多了一个参数supermanCtrl,这个参数猜想是superman中的controller,所以命名采用superman+Ctrl的方式。
【由于不懂内部原理,这里仅仅是猜想,但是实验证明,如果改变这个参数的名字,会报错。】
声明了这三个指令,就可以把这三个指令当做super的属性来使用,当注明该属性时,就会触发内部的link内的方法,调用superman中公开的方法。
总结起来,指令的交互过程:
1 首先创建一个基本的指令,在controller属性后,添加对外公开的方法。
2 创建其他交互的指令,在require属性后,添加对应的指令依赖关系;在link中调用公开的方法
全部程序代码:
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 邓丽君.1983-漫步人生路(2024环球MQA-UHQCD限量版)【环球】【WAV+CUE】
- 陈容森.1996-情断【上华】【WAV+CUE】
- 裘海正.1994-爱我的人和我爱的人【上华】【WAV+CUE】
- 庾澄庆.1988-错过的爱【福茂】【WAV+CUE】
- 班得瑞原装进口《第十三张新世纪专辑:旭日之丘》1CD[APE/CUE分轨][329.6MB]
- 纯音入心系列纯音乐《古筝|佛蕴|境法禅心意法自然》1CD[MP3][350MB]
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[320K/MP3][203.44MB]
- 群星.1981-名曲65(2014环球复黑王·百代篇)【EMI百代】【WAV+CUE】
- 陈淑桦.1990-娃娃的故事【柯达】【WAV+CUE】
- 戴梅君.2011-问签诗【美华】【WAV+CUE】
- 李国祥.1995-九五变奏【嘉音】【WAV+CUE】
- 许景淳.1992-你来自何方【全美唱片】【WAV+CUE】
- 石欣卉.2007-剧欣卉集·完整电视剧主题精丫华纳】【WAV+CUE】
- 群星.2005-LOVE情歌集VOL.5.2CD【正东】【WAV+CUE】
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】