在AngularJS中使用自定義指令來擴展HTML的功能。使用“指令”功能定義自定義指令。自定義指令僅替換被激活的元素。引導期間AngularJS應用程序會找到匹配的元素,并使用其compile()custom指令的方法進行一次活動,然后link()根據(jù)指令的范圍使用custom指令的方法處理該元素。AngularJS支持為以下類型的元素創(chuàng)建自定義指令。
元素指令 ?遇到匹配元素時,指令將激活。
屬性 ?遇到匹配屬性時,指令將激活。
CSS ?遇到匹配的CSS樣式時,指令將激活。
注釋 ?遇到匹配的注釋時,指令將激活。
定義自定義html標簽。
<student name = "Sea"></student><br/><student name = "Piyush"></student>
定義自定義指令以處理上述自定義html標簽。
var mainApp = angular.module("mainApp", []);
//創(chuàng)建一個指令,第一個參數(shù)是要附加的html元素。
//我們將附加學生html標簽。
//一旦在html中遇到任何Student元素,此指令將被激活
mainApp.directive('student', function() {
//定義指令對象
var directive = {};
//limit = E,表示該指令是Element指令
directive.restrict = 'E';
//模板將完整元素替換為其文本。
directive.template = "Student: <b>{{student.name}}</b> ,
Roll No: <b>{{student.rollno}}</b>";
//作用域用于根據(jù)條件區(qū)分每個學生元素。
directive.scope = {
student : "=name"
}
//在應用程序初始化期間調用compile。AngularJS調用
it once when html page is loaded.
directive.compile = function(element, attributes) {
element.css("border", "1px solid #cccccc");
//linkFunction與具有范圍的每個元素鏈接以獲得元素特定的數(shù)據(jù)。
var linkFunction = function($scope, element, attributes) {
element.html("Student: <b>"+$scope.student.name +"</b> ,
Roll No: <b>"+$scope.student.rollno+"</b><br/>");
element.css("background-color", "#ff00ff");
}
return linkFunction;
}
return directive;
});定義控制器以更新指令的范圍。在這里,我們使用name屬性的值作為作用域的子級。
mainApp.controller('StudentController', function($scope) {
$scope.Sea = {};
$scope.Sea.name = "Sea Gull";
$scope.Sea.rollno = 1;
$scope.Piyush = {};
$scope.Piyush.name = "Piyush Gull";
$scope.Piyush.rollno = 2;
});<html>
<head>
<title>AngularJS-自定義指令</title>
</head>
<body>
<h2>AngularJS-自定義指令示例</h2>
<div ng-app = "mainApp" ng-controller = "StudentController">
<student name = "Sea"></student><br/>
<student name = "Piyush"></student>
</div>
<script src = "https://cdn.staticfile.org/angular.js/1.3.14/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.directive('student', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>";
directive.scope = {
student : "=name"
}
directive.compile = function(element, attributes) {
element.css("border", "1px solid #cccccc");
var linkFunction = function($scope, element, attributes) {
element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>");
element.css("background-color", "#ff00ff");
}
return linkFunction;
}
return directive;
});
mainApp.controller('StudentController', function($scope) {
$scope.Sea = {};
$scope.Sea.name = "Sea Gull";
$scope.Sea.rollno = 1;
$scope.Piyush = {};
$scope.Piyush.name = "Piyush Gull";
$scope.Piyush.rollno = 2;
});
</script>
</body>
</html>測試看看?/?輸出結果
在網絡瀏覽器中打開textAngularJS.htm。查看結果。