在AngularJS中使用自定义指令来扩展HTML的功能。使用“指令”功能定义自定义指令。自定义指令仅替换被激活的元素。引导期间AngularJS应用程序会找到匹配的元素,并使用其compile()
custom指令的方法进行一次活动,然后link()
根据指令的范围使用custom指令的方法处理该元素。AngularJS支持为以下类型的元素创建自定义指令。
元素指令
−遇到匹配元素时,指令将激活。属性
−遇到匹配属性时,指令将激活。CSS
−遇到匹配的CSS样式时,指令将激活。注释
−遇到匹配的注释时,指令将激活。
了解自定义指令
定义自定义html标签。
<student name = "Sea"></student><br/><student name = "Piyush"></student>
定义自定义指令以处理上述自定义html标签。
var mainApp = angular.module("mainApp", []);
//创建一个指令,第一个参数是要附加的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>";
//作用域用于根据条件区分每个学生元素。
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与具有范围的每个元素链接以获得元素特定的数据。
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。查看结果。