📜  AngularJS-自定义指令

📅  最后修改于: 2020-10-27 02:54:15             🧑  作者: Mango


在AngularJS中使用自定义指令来扩展HTML的功能。自定义指令是使用“指令”函数定义的。自定义指令仅替换被激活的元素。引导过程中,AngularJS应用程序会找到匹配的元素,并使用其自定义指令的compile()方法进行一次活动,然后根据该指令的范围使用自定义指令的link()方法处理该元素。 AngularJS支持为以下类型的元素创建自定义指令。

  • 元素指令-当遇到匹配的元素时,指令将激活。

  • 属性-当遇到匹配的属性时,指令将激活。

  • CSS-指令在遇到匹配的CSS样式时激活。

  • 注释-遇到匹配的注释时,指令将激活。

了解自定义指令

定义自定义html标签。


定义自定义指令以处理上述自定义html标签。

var mainApp = angular.module("mainApp", []);

//Create a directive, first parameter is the html element to be attached.      
//We are attaching student html tag. 
//This directive will be activated as soon as any student element is encountered in html

mainApp.directive('student', function() {
   //define the directive object
   var directive = {};
   
   //restrict = E, signifies that directive is Element directive
   directive.restrict = 'E';
   
   //template replaces the complete element with its text. 
   directive.template = "Student: {{student.name}} , 
      Roll No: {{student.rollno}}";
   
   //scope is used to distinguish each student element based on criteria.
   directive.scope = {
      student : "=name"
   }
   
   //compile is called during application initialization. AngularJS calls 
      it once when html page is loaded.
    
   directive.compile = function(element, attributes) {
      element.css("border", "1px solid #cccccc");
      
      //linkFunction is linked with each element with scope to get the element specific data.
      var linkFunction = function($scope, element, attributes) {
         element.html("Student: "+$scope.student.name +" , 
            Roll No: "+$scope.student.rollno+"
"); 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;
});

Angular JS Custom Directives
   
   
   
      

AngularJS Sample Application


输出

在网络浏览器中打开textAngularJS.htm 。查看结果。