除了 AngularJS 內(nèi)置的指令外,我們還可以創(chuàng)建自定義指令。
你可以使用 .directive 函數(shù)來(lái)添加自定義的指令。
要調(diào)用自定義指令,HTML 元素上需要添加自定義指令名。
使用駝峰法來(lái)命名一個(gè)指令, runoobDirective, 但在使用它時(shí)需要以 - 分割, runoob-directive:
AngularJS 實(shí)例
<body ng-app="myApp">
<runoob-directive></runoob-directive>
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
template : "<h1>自定義指令!</h1>"
};
});
</script>
</body>
你可以通過(guò)以下方式來(lái)調(diào)用指令:
- 元素名
- 屬性
- 類(lèi)名
- 注釋
限制使用:你可以限制你的指令只能通過(guò)特定的方式來(lái)調(diào)用。
restrict 值可以是以下幾種:
- E 作為元素名使用
- A 作為屬性使用
- C 作為類(lèi)名使用
- M 作為注釋使用
restrict 默認(rèn)值為 EA, 即可以通過(guò)元素名和屬性名來(lái)調(diào)用指令。
angular自定義指令的兩種寫(xiě)法:
上面這種,感覺(jué)更清晰明確一點(diǎn)。
// angular.module('MyApp',[])
// .directive('zl1',zl1)
// .controller('con1',['$scope',func1]);
//
// function zl1(){
// var directive={
// restrict:'AEC',
// template:'this is the it-first directive',
// };
// return directive;
// };
//
// function func1($scope){
// $scope.name="alice";
// }
//這是教程里類(lèi)似的寫(xiě)法
angular.module('myApp',[]).directive('zl1',[ function(){
return {
restrict:'AE',
template:'thirective',
link:function($scope,elm,attr,controller){
console.log("這是link");
},
controller:function($scope,$element,$attrs){
console.log("這是con");
}
};
}]).controller('Con1',['$scope',function($scope){
$scope.name="aliceqqq";
}]);
還有指令配置項(xiàng)的:link controller等在項(xiàng)目運(yùn)用中有遇到過(guò):
angular.module('myApp', []).directive('first', [ function(){
return {
// scope: false, // 默認(rèn)值,共享父級(jí)作用域
// controller: function($scope, $element, $attrs, $transclude) {},
restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment
template: 'first name:{{name}}',
};
}]).directive('second', [ function(){
return {
scope: true, // 繼承父級(jí)作用域并創(chuàng)建指令自己的作用域
// controller: function($scope, $element, $attrs, $transclude) {},
restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment
//當(dāng)修改這里的name時(shí),second會(huì)在自己的作用域中新建一個(gè)name變量,與父級(jí)作用域中的
// name相對(duì)獨(dú)立,所以再修改父級(jí)中的name對(duì)second中的name就不會(huì)有影響了
template: 'second name:{{name}}',
};
}]).directive('third', [ function(){
return {
scope: {}, // 創(chuàng)建指令自己的獨(dú)立作用域,與父級(jí)毫無(wú)關(guān)系
// controller: function($scope, $element, $attrs, $transclude) {},
restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment
template: 'third name:{{name}}',
};
}])
.controller('DirectiveController', ['$scope', function($scope){
$scope.name="mike";
}]);