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>