Пользовательские директивы используются в AngularJS для расширения функциональности HTML. Пользовательские директивы определяются с помощью функции «директива». Пользовательская директива просто заменяет элемент, для которого он активирован. Приложение AngularJS во время загрузки загружает совпадающие элементы и выполняет однократное действие, используя свой метод compile() настраиваемой директивы, а затем обрабатывает элемент с помощью метода link () настраиваемой директивы на основе области действия директивы. AngularJS обеспечивает поддержку для создания настраиваемых директив для следующих типов элементов.

  • Директивы элементов - Директива активируется, когда встречается соответствующий элемент.
  • Атрибут - Директива активируется , когда атрибут соответствия встречается.
  • CSS - Директива активируется, когда встречается соответствующий стиль css.
  • Комментарий - директива активируется, когда встречается соответствующий комментарий.

Внимание!!!

Если примеры не отображаются на странице или искажены, проверьте не блокирует ли их браузер!

Opera

Свободу АНГУЛЯРУ в Opera!!! )))

Google Chrome

Свободу АНГУЛЯРУ в Google Chrome!!! )))

Mozilla Firefox

Свободу АНГУЛЯРУ в Mozilla Firefox!!! )))

Yandex

Свободу АНГУЛЯРУ в Yandex!!! )))

Понимание пользовательской директивы

Определите пользовательские теги html.

<student name = "Ivan"></student>

<student name = "Ivanov"></student>

Определите настраиваемую директиву для обработки над пользовательскими тегами 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: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>";
  
   //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: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b>
");
         element.css("background-color", "#ff00ff");
      }
      return linkFunction;
   }
   return directive;
});

Определите контроллер для обновления области действия директивы. Здесь мы используем значение атрибута name как дочерний объект.

mainApp.controller('StudentController', function($scope) {
   $scope.Ivan = {};
   $scope.Ivan.name = "Ivan Ivanov";
   $scope.Ivan.rollno  = 1;
  
   $scope.Petr = {};
   $scope.Petr.name = "Petr Petrov";
   $scope.Petr.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 = "Ivan Ivanov"></student>

         <student name = "Petr Petrov"></student>
      </div>
                       
      <script src = "http://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>
");
                  element.css("background-color", "#ff00ff");
               }
               return linkFunction;
            }
           
            return directive;
         });
        
         mainApp.controller('StudentController', function($scope) {
            $scope.Mahesh = {};
            $scope.Mahesh.name = "Ivan Ivanov";
            $scope.Mahesh.rollno  = 1;
 
            $scope.Piyush = {};
            $scope.Piyush.name = "Petr Petrov";
            $scope.Piyush.rollno  = 2;
         });
                                    
      </script>
     
   </body>
</html>

Результат

Откройте textAngularJS.htm в веб-браузере.




Понравилась статья? Поделитесь ею с друзьями и напишите отзыв в комментариях!

We use cookies on our website. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.

Ok