版权声明:本文为博主原创文章,未经博主允许不得转载。 //blog.csdn.net/qq_27626333/article/details/52261409
除了 AngularJS 内置的63个指令外,我们还可以创建自定义指令。你可以使用 .directive 函数来添加自定义的指令。要调用自定义指令,HTML 元素上需要添加自定义指令名。使用驼峰法来命名一个指令, runoobDirective, 但在使用它时需要以 - 分割, runoob-directive,自定义指令的参数如下:
- angular.module(‘app‘,[]).directive(‘myDirective‘,function(){
- return{
- restrict:String,
- priority:Number,
- terminal:Boolean,
- template:StringorTemplateFunction,
- templateUrl:StringorTemplateFunction,
- replace:BooleanorString,
- transclude:Boolean,
- scope:BooleanorObject,
- controller:Stringorfunction(scope,element,attrs,transclude,otherInjectables){...},
- controllerAs:String,
- require:String,
- link:function(scope,iElement,iAttrs){...},
- compile:function(tElement,tAttrs,transclude){
- return{
- pre:function(scope,iElement,iAttrs,controller){...},
- post:function(scope,iElement,iAttrs,controller){...}
- }
- returnfunctionpostLink(...){...}
- }
- };
- });
1、restrict:String
restrict是申明标识符在模板中作为元素,属性,类,注释或组合,如何使用。有四个值:E、A、C、M
注意:
(1)、推荐使用元素和属性的方式使用指令
(2)、当需要创建带有自己的模板的指令时,使用元素名称的方式创建指令
(3)、当需要为已有的HTML标签增加功能时,使用属性的方式创建指令
实例:
- <!doctypehtml>
- <htmlng-app="MyModule">
- <head>
- <metacharset="utf-8">
- </head>
- <body>
- <hello></hello>
- <divhello></div>
- <div></div>
- <!--directive:hello-->
- </body>
- <scriptsrc="framework/angular-1.3.0.14/angular.js"></script>
- <script>
- varmyModule=angular.module("MyModule",[]);
- myModule.directive("hello",function(){
- return{
- restrict:‘AEMC‘,
- template:‘<div>Hieveryone!</div>‘,
- replace:true
- }
- });
- </script>
- </html>
2、priority: Number
priority是指令执行优先级。若在单个DOM上有多个指令,则优先级高的先执行;
设置指令的优先级算是不常用的
3、template: Stringor Function
(1)、字符串
template是指令链接DOM模板
- <!doctypehtml>
- <htmlng-app="MyModule">
- <head>
- <metacharset="utf-8">
- </head>
- <body>
- <hello></hello>
- </body>
- <scriptsrc="framework/angular-1.3.0.14/angular.js"></script>
- <script>
- varmyModule=angular.module("MyModule",[]);
- myModule.directive("hello",function(){
- return{
- restrict:‘E‘,
- template:‘<div>helloworld</div>‘,
- replace:true
- }
- });
- </script>
- </html>
(2)、函数
Function一个函数,可接受两个参数tElement和tAttrs。其中tElement是指使用此指令的元素,而tAttrs则实例的属性,它是一个由元素上所有的属性组成的集合(对象)形如:
- {
- name:‘shanshuizinong,
- age:23
- }
- <!doctypehtml>
- <htmlng-app="MyModule">
- <head>
- <metacharset="utf-8">
- </head>
- <body>
- <helloname=‘shanshuizinong‘></hello>
- </body>
- <scriptsrc="js/angular.min.js"></script>
- <script>
- varmyModule=angular.module("MyModule",[]);
- myModule.directive("hello",function(){
- return{
- restrict:‘E‘,
- replace:true,
- template:function(tElement,tAttrs){
- varhtml=‘‘;
- html+=‘<div>‘+tAttrs.name+‘</div>‘;
- returnhtml;
- }
- }
- });
- </script>
- </html>
4、emplateUrl: String
templateUrl是指定一个字符串式的内嵌模板,如果你指定了模板是一个URL,那么是不会使用的。
- <!doctypehtml>
- <htmlng-app="MyModule">
- <head>
- <metacharset="utf-8">
- <linkrel="stylesheet"href="css/bootstrap-3.0.0/css/bootstrap.css">
- </head>
- <body>
- <hello></hello>
- </body>
- <scriptsrc="framework/angular-1.3.0.14/angular.js"></script>
- <scripttype="text/javascript">
- varmyModule=angular.module("MyModule",[]);
- myModule.directive("hello",function(){
- return{
- restrict:‘AECM‘,
- templateUrl:‘hello.html‘,
- replace:true
- }
- });
- </script>
- </html>
由于加载html模板是通过异步加载的,若加载大量的模板会拖慢网站的速度,这里有个技巧,就是先缓存模板。
- <!doctypehtml>
- <htmlng-app="MyModule">
- <head>
- <metacharset="utf-8">
- </head>
- <body>
- <hello></hello>
- </body>
- <scriptsrc="framework/angular-1.3.0.14/angular.js"></script>
- <scripttype="text/javascript">
- varmyModule=angular.module("MyModule",[]);
- //注射器加载完所有模块时,此方法执行一次;缓存
- myModule.run(function($templateCache){
- $templateCache.put("hello.html","<div>Helloworld!!!</div>");
- });
- myModule.directive("hello",function($templateCache){
- return{
- restrict:‘AECM‘,
- template:$templateCache.get("hello.html"),
- replace:true
- }
- });
- </script>
- </html>
5、replace: Boolean
replace是指令链接模板是否替换原有元素
- <!doctypehtml>
- <htmlng-app="MyModule">
- <head>
- <metacharset="utf-8">
- </head>
- <body>
- <hello>
- <div>这里是指令内部的内容。</div>
- </hello>
- </body>
- <scriptsrc="js/angular.min.js"type="text/javascript"charset="utf-8"></script>
- <scripttype="text/javascript">
- varmyModule=angular.module("MyModule",[]);
- myModule.directive("hello",function(){
- return{
- restrict:"AE",
- template:"<div>HelloWorld!</div>",
- replace:true
- }
- });
- </script>
- </html>
6、transclude: Boolean
transclude是移动一个标识符的原始字节带到一个新模块的位置。当你开启transclude后,你就可以使用ng-transclude来指明了应该在什么地方放置transcluded内容。
- <!doctypehtml>
- <htmlng-app="MyModule">
- <head>
- <metacharset="utf-8">
- </head>
- <body>
- <hello>
- <div>这里是指令内部的内容。</div>
- </hello>
- </body>
- <scriptsrc="js/angular.min.js"></script>
- <scripttype="text/javascript">
- varmyModule=angular.module("MyModule",[]);
- myModule.directive("hello",function(){
- return{
- restrict:"AE",
- transclude:true,
- template:"<div>Helloeveryone!<divng-transclude>你看不见我</div></div>"
- }
- });
- </script>
- </html>
7、link:Function
link通过代码修改目标DOM元素的实例,添加事件监听,建立数据绑定。compile函数用来对模板自身进行转换,而link函数负责在模型和视图之间进行动态关联;compile函数仅仅在编译阶段运行一次,而对于指令的每个实例,link函数都会执行一次;compile可以返回preLink和postLink函数,而link函数只会返回postLink函数,如果需要修改DOM结构,应该在postLink中来做这件事情,而如果在preLink中做这件事情会导致错误;大多数时候我们只要编写link函数即可。
link函数有四个参数分别为:
(1)scope,与指令元素相关联的作用域
(2)element,当前指令对应的 元素
(3)attrs,由当前元素的属性组成的对象
(4)supermanCtrl,若指令中定义有require选项,则会有supermanCtrl参数,代表控制器或者所依赖的指令的控制器。
- <!doctypehtml>
- <htmlng-app="MyModule">
- <head>
- <metacharset="utf-8">
- </head>
- <body>
- <hello>HelloWorld!</hello>
- </body>
- <scriptsrc="js/angular.min.js"></script>
- <scripttype="text/javascript">
- varmyModule=angular.module("MyModule",[]);
- myModule.directive("hello",function(){
- return{
- restrict:"AE",
- link:function(scope,element,attrs,supermanCtrl){
- console.log(element);
- element.bind("mouseenter",function(){
- console.log("鼠标进入...");
- });
- element.bind("mouseout",function(){
- console.log("鼠标滑出...");
- });
- }
- }
- });
- </script>
- </html>
下面实例通过link函数实现指令的复用,两个控制器与一个指令之间进行交互。指令可以调用控制器MyCtrl和MyCtrl2中的方法,但是需要注意我们必须使用属性,因为两个控制器的方法不同。
- <!doctypehtml>
- <htmlng-app="MyModule">
- <head>
- <metacharset="utf-8">
- </head>
- <body>
- <divng-controller="MyCtrl">
- <loaderhowToLoad="loadData()">滑动加载</loader>
- </div>
- <divng-controller="MyCtrl2">
- <loaderhowToLoad="loadData2()">滑动加载</loader>
- </div>
- </body>
- <scriptsrc="framework/angular-1.3.0.14/angular.js"></script>
- <scripttype="text/javascript">
- varmyModule=angular.module("MyModule",[]);
- myModule.controller(‘MyCtrl‘,[‘$scope‘,function($scope){
- $scope.loadData=function(){
- console.log("加载数据中111...");
- }
- }]);
- myModule.controller(‘MyCtrl2‘,[‘$scope‘,function($scope){
- $scope.loadData2=function(){
- console.log("加载数据中222...");
- }
- }]);
- myModule.directive("loader",function(){
- return{
- restrict:"AE",
- link:function(scope,element,attrs){
- element.bind(‘mouseenter‘,function(event){
- //注意这里的坑,howToLoad会被转换成小写的howtoload
- scope.$apply(attrs.howtoload);
- });
- }
- }
- });
- </script>
- </html>
8、controller和require
(1)、controller
controller创建一个控制器通过标识符公开通信API。给指令暴露出一组public方法,给外部调用的。
1)、字符串
若是为字符串,则将字符串当做是控制器的名字,来查找注册在应用中的控制器的构造函数
- angular.module(‘myApp‘,[]).directive(‘myDirective‘,function(){
- restrict:‘A‘,
- controller:‘SomeController‘
- })
- angular.module(‘myApp‘).controller(‘SomeController‘,function($scope,$element,$attrs,$transclude){
- //控制器逻辑放在这里
- });
2)、匿名函数
也可以直接在指令内部的定义为匿名函数,同样我们可以再这里注入任何服务($log,$timeout等等)
- angular.module(‘myApp‘,[]).directive(‘myDirective‘,function(){
- restrict:‘A‘,
- controller:function($scope,$element,$attrs,$transclude){
- //控制器逻辑放在这里
- }
- });
另外还有一些特殊的服务(参数)可以注入
(a)$scope,与指令元素相关联的作用域
(b)$element,当前指令对应的元素
(c)$attrs,由当前元素的属性组成的对象
(d)$transclude,嵌入链接函数,实际被执行用来克隆元素和操作DOM的函数
注意: 除非是用来定义一些可复用的行为,一般不推荐在这使用。
指令的控制器和link函数可以进行互换。区别在于,控制器主要是用来提供可在指令间复用的行为但link链接函数只能在当前内部指令中定义行为,且无法再指令间复用。
下面是实例js中包含controller的一部分:定义了三个公共方法,供外部指令访问。
- varmyModule=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(‘btnbtn-primary‘);
- element.bind("mouseenter",function(){
- console.log(scope.abilities);
- });
- }
- }
- });
(2)、require
require当前标识符需要另一个标识符提供正确的函数功能。require的值可以是字符串或者数组。字符串代表另一个指令的名字,它将会作为link函数的第四个参数。controller的用法分为两种情形,一种是require自定义的controller,由于自定义controller中的属性方法都由自己编写,使用起来比较简单;另一种方法则是require AngularJS内建的指令,其中大部分时间需要require的都是ngModel这个指令。
下面是实例程序:假设现在我们要编写三个指令,三个指令中的link链接函数中存在有很多重合的方法,这时候我们就可以将这些重复的方法写在一个指令的controller中。然后在这三个指令中,require这个拥有controller字段的的指令,最后通过link链接函数的第四个参数就可以引用这些重合的方法了。
- <!doctypehtml>
- <htmlng-app="MyModule">
- <head>
- <metacharset="utf-8">
- <linkrel="stylesheet"href="css/bootstrap-3.0.0/css/bootstrap.css">
- <scriptsrc="js/angular.min.js"></script>
- </head>
- <body>
- <div>
- <div>
- <supermanstrength>动感超人---力量</superman>
- </div>
- </div><br>
- <div>
- <div>
- <supermanstrengthspeed>动感超人2---力量+敏捷</superman>
- </div>
- </div><br>
- <div>
- <div>
- <supermanstrengthspeedlight>动感超人3---力量+敏捷+发光</superman>
- </div>
- </div>
- </body>
- <scripttype="text/javascript">
- varmyModule=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(‘btnbtn-primary‘);
- element.bind("mouseenter",function(){
- console.log(scope.abilities);
- });
- }
- }
- });
- myModule.directive("strength",function(){
- return{
- require:‘^superman‘,
- link:function(scope,element,attrs,supermanCtrl){
知识推荐
- firewalld和netfilter
- HttpWatch功能详细介绍
- html
- js函数的两种定义形式,函数的实参列表arguments/形参列表函数名
- 在ASP.NET CORE 2.0使用SignalR技术
- ●BZOJ 1444 [Jsoi2009]有趣的游戏
- ABP Error in roboto.css can't resolve '97uahxiqZRoncBaCEI3aWxJtnKITppOI_IvcXXDNrsc.woff2'
- (转)写的非常好的一篇HTTP协议详解
- 整理笔记--CSS
- js中判断对象的数据类型
- JaveScript内置对象(JS知识点归纳八)
- web爬虫之登录google paly 商店
- CSRF之Ajax请求
- jsp 文件无法加载 css、js 的问题
- ie 已限制此网页运行脚本或Active控件
- webpack 效率及性能提升
- kubernetes组成
- Coursera Deep Learning 3 Convolutional Neural Networks - week1