AngularJS自定义指令Custom Directives
时间:2021-11-29 作者:匿名
自定义指令用于AngularJS扩展HTML的功能。 自定义指令定义使用“指令”功能。 自定义指令简单地取代它被激活的元素。 AngularJS应用在引导发现匹配的元素和做一次活动使用的编译()方法定义指令然后处理元素使用的链接()方法定义指令基于指令的范围。 AngularJS提供支持创建自定义指令为以下类型的元素。
1、元素指示Element directives−指令激活时遇到一个匹配的元素。
2、属性Attribute−指令激活当遇到匹配的属性。
3、CSS−指令激活当遇到匹配的css样式。
4、评论Comment−指令激活当遇到匹配的评论。
理解自定义指令
定义定制的html标记。
<student name = "Mahesh"></student><br/> <student name = "Piyush"></student>
定义自定义指令以处理上述自定义html标记。
var mainApp = angular.module("mainApp", []); //创建一个指令,第一个参数是要附加的html元素。 //我们正在附加学生html标签。 //一旦在html中遇到任何student元素,就会激活此指令 mainApp.directive('student', function() { //定义指令对象 var directive = {}; //restrict=E,表示指令是元素指令 directive.restrict = 'E'; //模板用其文本替换整个元素。 directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>"; //范围用于根据标准区分每个student元素。 directive.scope = { student : "=name" } //在应用程序初始化期间调用compile。AngularJS呼叫在加载html页面时,它只显示一次。 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; });
实例
textAngularJS.htm
<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://www.yangzhiw.cn/static/js/angularjs-1.5.8/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>
输出
在浏览器中打开textAngularJS.htm后显示: