ng自定义指令只有一种方法,通过directive去定义声明,使用有四种方法,作为元素、属性、class类、注释。以返回一个对象的方式定义。需要注意是名称必须以驼峰式命名,使用时变横杠的方式,比如名称为:myTest, 使用: my-test。ng内置的指令也是这么用的。
自定义指令的常用的属性有这么一些:name priority terminal scope controller require restrict template replace transclude compile link等。
<body ng-controller="myContr">
<!--作为标签使用-->
<my-test></my-test>
<!--作为属性使用-->
<div my-test></div>
<!--作为class类使用-->
<div class="my-test"></div>
<!--作为注释使用-->
<!-- directive:my-test -->
<script>
//声明ng模块
var app=angular.module("myModule",['ng']);
//自定义指令,两个参数,第一个参数为指令的名称,第二参数为设置指令的function
app.directive("myTest",function(){
return{
template:'<h1>Hello world</h1>',
restrict:"EACM",//指定四种使用模式,E/element A/attribute C/class M/comment
replace:'true' //作为注释使用,由于注释本就不显示的特殊性,需要用replace替换
}
});
</script>
需要传参的自定义指令
<body ng-controller="myContr">
<!--作为属性使用-->
<div my-test test="Hello world"> </div>
<!--作为元素使用-->
<my-test test="Hello world"> </my-test>
<script>
var app=angular.module("myModule",['ng']);
app.directive("myTest",function(){
return{
template:'<p>{{test}}</p>', 绑定接收参数的变量test
scope:{ //scope属性声明一块作用域,用来存储变量接收传过来的参数值
test:'@' //@符号相当形参 test为变量
}
}
});
</script>
</body>