創建一個模塊
var app = angular.module('app', []);
創建一個簡單指令標籤
app.directive('alert', function(){
return {
template: '<div class="alert">' +
'<span class="alert-topic">' +
'something went wrong!' +
'</span>' +
'<span class="alert-description">' +
'You must inform the plate and the color of the car!' +
'</span>' +
'</div>'
};
});
使用templateUrl,創建指令標籤
app.directive('alert', function(){
return {
templateUrl: 'template/alert.html'
};
});
template目錄下alert.html代碼如下:
<div class="alert">
<span class="alert-topic">
Something went wrong!
</span>
<span class="alert-description">
You must inform the plate and the color of the car!
</span>
</div>
replace屬性,控制是否替換原來的標籤元素: true/false
restrict屬性,聲明指令標籤以何種方式出現在HTML標籤中。
如下示例:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<alert></alert>
<script src="js/angular/angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.directive('alert', function(){
return {
templateUrl: 'template/alert.html',
replace: true,
restrict: 'E'
};
});
</script>
</body>
</html>
可以同時使用‘AECM’中的多個或全部。
scope屬性
前面將自定義指令標籤的內容通過硬編碼的形式直接寫在模板裏,這種方式有其侷限性。
而通過scope屬性,可以將指令標籤顯示的內容與模板分離,然後通過綁定的方式將其關聯起來。如下:
(1)JS部分:
var app = angular.module('app', []);
app.directive('alert', function(){
return {
templateUrl: 'template/alert.html',
replace: true,
restrict: 'E',
scope: {
topic: '@topic',
description: '@description'
}
};
});
(2)alert.html模板部分
<div class="alert">
<span class="alert-topic">
<span ng-bind="topic"></span>
</span>
<span class="alert-description">
<span ng-bind="description"></span>
</span>
</div>
(3)在頁面中使用該標籤實例:
<alert topic="Action!" description="You must inform the plate and the color of the car!"></alert>