這片文章為directive的基本的用法虑省。
1.directive的定義
angular.module("app",[]).directive("directiveName",function(){
return{
//通過設(shè)置項(xiàng)來定義
};
})
2.directive的聲明方式
E:元素
A:屬性
C:樣式
D:注釋
目前我自己經(jīng)歷過的項(xiàng)目中沒見過過第四種寫法泻骤,前兩種聲明方式比較常見。
3.directive 的template和templateUrl參數(shù)
angular.module("app",[]).directive("hello",function(){? ? ? ? ? ? ? ??
? ? return{? ? ? ? ? ? ? ??
? ? ? ? ?restrict:'EA',? ? ? ? ? ? ? ??
? ? ? ? ?template:"
? ? ? ? ? ? hello world
? ? ? ? ?"? ? ? ? ? ? ? ??
? ? };? ? ? ? ? ??
})
template內(nèi)容可以用templateUrl替換祷杈,建議使用后者兵罢。
4.replace參數(shù)
設(shè)為true后变抽,指令所在位置都會(huì)被template或者templateUrl替換。
5.transclude參數(shù)
var appModule = angular.module('app', []);? ??
appModule.directive('hello', function() {? ??
? ? return {? ? ? ??
? ? ? ? restrict: 'E',? ? ? ??
? ? ? ? template: '在前面的',? ? ? ??
? ? ? ? transclude: true? ??
? ? };
});
被指令包裹的內(nèi)容會(huì)在template下面顯示束昵。
<hello>
? ? <br/>
? ? ?后面
</hello>
界面會(huì)顯示:
在前面的
后面
5.scope
可選參數(shù),(布爾值或者對(duì)象)默認(rèn)值為false葛峻,可能取值:
(1)默認(rèn)值false锹雏。
表示繼承父作用域;
(2)true
表示繼承父作用域,并創(chuàng)建自己的作用域(子作用域);父親改了子也該术奖,子改了父親不改礁遵。
(3){}
表示創(chuàng)建一個(gè)全新的隔離作用域;各自有各自作用域采记。
當(dāng)設(shè)置為{}時(shí)佣耐,兩個(gè)作用域分開了,如何在兩個(gè)directive上傳參數(shù)呢唧龄?
scope: {
? ? color: '@'
}
單向傳參兼砖。
scope:{
? ? color:'='
}
雙向傳參
scope:{
? ? saysomething:'&',
},
函數(shù)的傳遞
6.compile和link
compile階段進(jìn)行標(biāo)簽解析和變換,link階段進(jìn)行數(shù)據(jù)綁定等操作》硇可在link上進(jìn)行事件綁定懒叛。