AngularJS提供了一系列的内置指令,如ng开头的指令,同时AngularJS也允许用户自定义指令。
目录:
1.自定义指令
2.使用自定义指令
3.自定义指令的内嵌使用
自定义指令
AngularJS中使用directive()方法来自定义指令,directive() 方法可以接受两个参数:
name(字符):指令的名字,用来在视图中引用特定的指令
factory_function(函数):这个函数返回一个对象,其中定义了指令的全部行为
例如:创建一个test指令:
var app = angular.module('myApp',[]);
app.directive('hello',function(){
return {
restrict:'AECM',
template:'hello world',
replace:true
};
});
说明:
在directive方法的第二个函数参数中,返回了一个对象,字段的意义如下:
restrice:定义了标签的使用方法,一共四种,分别是AECM
template:定义标签的模板。里面是用于替换自定义标签的字符串
repalce:是否替换
另外还有transclude:标识是否嵌套
使用自定义指令
指令在html中的使用有4中方法,分别对应restrice的标签的4个使用方法AECM
A:属性
-------->hello world
E:元素
-------->hello world
C:样式(class的值)
"hello">------>hello world
M:注释
各个版本不一样
自定义指令的内嵌使用
app.directive('test',function(){
return {
restrict:'AECM',
template:'hello world',
transclude:true
};
});
说明:自定义指令的内嵌使用需要将transclude字段赋值为true,template中使用ng-transclude来确定内嵌的位置。
实例代码如下:
"myApp"> <head> "utf-8" /> head>0 12"hello">343333 54444