AngularJS 自定义指令
AngularJS 中使用自定义指令来扩展 HTML 的功能。自定义指令是使用“指令”函数定义的。自定义指令只是替换激活它的元素。 AngularJS 应用程序在引导过程中找到匹配的元素并使用自定义指令的 compile() 方法执行一次活动,然后根据指令的范围使用自定义指令的 link() 方法处理元素。 AngularJS 支持为以下类型的元素创建自定义指令。
-
元素指令 :指令在遇到匹配元素时激活。
-
属性 :指令在遇到匹配的属性时激活。
-
CSS :指令在遇到匹配的css样式时激活。
-
Comment :指令在遇到匹配的评论时激活。
了解自定义指令
定义自定义 html 标签。
<student name = "Mahesh"></student><br/> <student name = "Piyush"></student>
定义自定义指令以处理上述自定义 html 标记。
var mainApp = angular.module("mainApp", []); // 创建一个指令,第一个参数是要附加的html元素。 // 我们正在附加学生 html 标签。 // 只要在 html 中遇到任何学生元素,该指令就会被激活 mainApp.directive('student', function() { // 定义指令对象 var directive = {}; // restrict = 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.Mahesh = {}; $scope.Mahesh.name = "Mahesh Parashar"; $scope.Mahesh.rollno = 1; $scope.Piyush = {}; $scope.Piyush.name = "Piyush Parashar"; $scope.Piyush.rollno = 2; });
例子
<html> <head> <title>Angular JS Custom Directives</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "StudentController"> <student name = "Mahesh"></student><br/> <student name = "Piyush"></student> </div> <script src = "https:// ajax.googleapis.com/ajax/libs/angularjs/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.Mahesh = {}; $scope.Mahesh.name = "Mahesh Parashar"; $scope.Mahesh.rollno = 1; $scope.Piyush = {}; $scope.Piyush.name = "Piyush Parashar"; $scope.Piyush.rollno = 2; }); </script> </body> </html>
输出
Open 文本AngularJS.htm 在网络浏览器中。查看结果。