This article describes how to use custom commands in AngularJS, including using custom HTML tags. For more information, see use AngularJS in custom commands to extend HTML functions. Define the "command" function used by custom commands. The custom command only replaces the activated element. The AngularJS application finds matching elements during the guidance process, and completes the use of the custom command compile () method for one-time activity and re-processing using the command-based range custom command link () method element. AngularJS supports creating custom commands based on the types of the following columns of elements.
- Element ctictives-when the command encounters, a matching Element is activated.
- Attribute--a matching Attribute is activated when the command encounters.
- CSS--When the command encounters, the matching CSS style is activated.
- The Comment--command activates the matching annotation when it encounters.
Understand custom commands
Define custom HTML tags.
Define custom commands to process the preceding custom HTML tags.
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 htmlmainApp.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;});
Define the Controller to take the update range as the instruction. Here, we use the name attribute value as the sub-scope.
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;});
Example
Angular JS Custom direves vesAngularJS Sample Application