除了 AngularJS 內(nèi)置的指令外绰上,我們還可以創(chuàng)建自定義指令癣诱。
你可以使用 .directive 函數(shù)來添加自定義的指令窖式。
要調(diào)用自定義指令港柜,HTML 元素上需要添加自定義指令名。
使用駝峰法來命名一個(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>
你可以通過以下方式來調(diào)用指令:
- 元素名
- 屬性
- 類名
- 注釋
限制使用:你可以限制你的指令只能通過特定的方式來調(diào)用牢撼。
restrict 值可以是以下幾種:
- E 作為元素名使用
- A 作為屬性使用
- C 作為類名使用
- M 作為注釋使用
restrict 默認(rèn)值為 EA, 即可以通過元素名和屬性名來調(diào)用指令。
angular自定義指令的兩種寫法:
上面這種匈织,感覺更清晰明確一點(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";
// }
//這是教程里類似的寫法
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)用中有遇到過:
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í)毫無關(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";
}]);