Understanding AngularJs instructions _ AngularJS

Source: Internet
Author: User
This article mainly introduces the AngularJs command for instructions, which can be simply understood as a function running on a specific DOM element. commands can extend the function of this element.

First, let's look at a complete parameter example and introduce the functions and usage of each parameter in detail:

Angular. module ('myapp', []). directive ('myctive', function () {return {restrict: String, priority: Number, terminal: Boolean, template: String or Template Function: function (tElement, tAttrs) {...}, templateUrl: String, replace: Boolean or String, scope: Boolean or Object, transclude: Boolean, controller: String or function (scope, element, attrs, transclude, otherInjectables) {...}, controllerAs: String, require: String, link: function (scope, iElement, iAttrs ){...}, compile: // returns an object or connection function, as shown below: function (tElement, tAttrs, transclude) {return {pre: function (scope, iElement, iAttrs, controller) {...}, post: function (scope, iElement, iAttrs, controller ){...}} return function postLink (...) {...}}};});

1. restrict [string]

Restrict is an optional parameter. Specifies the form in which the command is declared in the DOM. The default value is A, which is declared as an attribute.
Optional values:
E (element)


A (attribute, default value)


C (class name)


M (comment)

<-- Directive: my-directive expression -->
Generally, considering the compatibility of the browser, we strongly recommend that you use the default attribute to declare it in the form of an attribute. We recommend that you do not use the final method when you do not want to force the grid index.

Code:

Angular. module ('app', []). directive ('myctive', function () {return {restrict: 'E', template: 'Baidu '};}) HtmlCode:
 

Effect:

2. priority [int]

Most commands ignore this parameter and use the default value 0. However, it is important or even necessary to set a high priority in some scenarios. For example, ngRepeat sets this parameter to 1000 to ensure that it is always called before other commands on the same element.

3. terminal [bool]

This parameter is used to stop running commands with a lower priority than the current command. However, commands with the same priority as the current command will still be executed.
For example, ngIf has a higher priority than ngView (which is actually the terminal parameter). If the expression value of ngIf is true, ngView can be executed normally, however, if the value of the ngIf expression is false, the ngView will not be executed because of its low priority.

4. template [string or function]

The template parameter is optional and must be set to one of the following two forms:

  • A piece of HTML text;
  • A function that accepts two parameters, tElement and tAttrs, and returns a string representing the template. T in tElement and tAttrs represents the template, which is relative to the instance.

First, demonstrate the second usage:

angular.module('app',[])  .directive('myDirective', function () {      return {         restrict: 'EAC',         template: function (elem, attr) {          return "" + attr.text + "";        }    };  })

HtmlCode: (the effect is the same as above. It is not demonstrated)

     

5. templateUrl [string or function]

TemplateUrl is an optional parameter and can be of the following types:

  • A string that represents the path of an external HTML file;
  • A function that accepts two parameters, tElement and tAttrs, and returns the string of an external HTML file path.

Either way, the template URL will be implemented through the ng built-in security layer, especially $ getTrustedResourceUrl, which can protect the template from being loaded by untrusted sources. By default, the HTML template file is requested through Ajax in the background when the command is called. Loading a large number of templates will seriously slow down the speed of a client application. To avoid latency, You Can cache the HTML template before deploying the application.

Code:

Angular. module ('app', []). directive ('myctive', function () {return {restrict: 'aes', templateUrl: function (elem, attr) {return attr. value + ". html "; // Of course, here we can directly specify the path, and the template can contain expressions }};})

6. replace [bool]

Replace is an optional parameter. If this parameter is set, the value must be true because the default value is false. The default value indicates that the template is inserted into the element that calls this command as a child element,
For example, if the default value of the preceding example is true, the generated html code is as follows:

 
  
Baidu
 

If replace = true is set

Baidu

As I have observed, this effect only works when restrict = "E" is set.

After introducing basic command parameters, we need to involve more important scope parameters...

7. scope parameter [bool or object]

The scope parameter is optional and can be set to true or an object. The default value is false.

If multiple commands on an element use an isolation scope, only one of them can take effect. Only the root element in the instruction template can obtain a new scope. Therefore, scope is set to true by default for these objects. The built-in instruction ng-controller is used to inherit from the parent-level scope and create a new sub-scope. It creates a new sub-scope inherited from the parent scope. The inheritance here is not detailed here. It is basically the same as the inheritance in object-oriented systems.

First, let's analyze a piece of code:

 

First generation: {name }}

Second generation: {name }}

Third generation: {name }}

We found that in the first generation, we initialized the name as the father, but the second and third generations are actually a scope, so their name is actually an object, so the effect is as follows:

Generation 1: Father
Generation 2: Sun Tzu
Third generation: Sun Tzu
We are modifying the code to isolate the Third Generation and then look at the effect:

First generation: {name }}

Second generation: {name }}

Third generation: {name }}

JsCode:

 angular.module('app', [])    .controller('SomeController',function($scope) {          })    .controller('SecondController', function ($scope) {      }) 

The effect is as follows:

Generation 1: Father
Generation 2: Son
Third generation: Sun Tzu
Modify the code to see the inheritance:

    

First generation: {name }}

Second generation: {name }}

Third generation: {name }}

The effect is as follows:

Generation 1: Grandfather's kiss
Second generation: Grandfather's kiss
Third generation: Grandfather's kiss

To create an instruction that can inherit the scope from an external prototype, set the scope attribute to true. In short, it is an inherited isolation, that is, the parent scope cannot be adversely affected.

Let's look at an example:

Angular. module ('myapp', []). controller ('maincontroller', function ($ scope ){}). directive ('myctive', function () {return {restrict: 'A', scope: false, // switch to {}, true test priority: 100, template :'

Internal: {myProperty }}

'};});

Html code:

 

External: {myProperty }}

When we change the scope value, we will find that

False: inherited but not isolated

True: Inherit and isolate

{}: Isolated and not inherited

8. transclude

Transclude is an optional parameter. The default value is false. Embedded is usually used to create reusable components. A typical example is a modal dialog box or navigation bar. We can embed all the commands in the template into one instruction. Commands can access the scope of External commands, and templates can also access external scope objects. To pass the scope, the scope parameter value must be set to an isolation scope through {} or true. If the scope parameter is not set, the internal scope of the instruction is set as the scope of the input template.

Transclude: true is used only when you want to create an instruction that contains any content.

Let's take a look at two examples-navigation bar:

Graphics ng D3 Front-end Startup

JsCode:

 angular.module('myApp', [])  .directive('sideBox', function() {    return {      restrict: 'EA',      scope: {        title: '@'      },      transclude: true,      template: '

' + '{{ title }}

' }; });

This code tells the ng compiler to place the content it obtains from the DOM element where it finds the ng-transclude command.

Let's look at an example on the official website:

angular.module('docsIsoFnBindExample', []) .controller('Controller', ['$scope', '$timeout', function($scope, $timeout) {  $scope.name = 'Tobias';  $scope.hideDialog = function () {   $scope.dialogIsHidden = true;   $timeout(function () {    $scope.dialogIsHidden = false;   }, 2000);  }; }]) .directive('myDialog', function() {  return {   restrict: 'E',   transclude: true,   scope: {    'close': '&onClose'   },   templateUrl: 'my-dialog-close.html'  }; });

My-dialog-close.html

×

Index.html

Check out the contents, {{name}}!

If the command uses the transclude parameter, the controller cannot monitor the data model changes normally. We recommend that you use the $ watch Service in the linked function.

9. controller [string or function]

The controller parameter can be a string or a function. When it is set as a string, the constructor of the controller registered in the application is searched based on the string value.

angular.module('myApp', []) .directive('myDirective', function() { restrict: 'A', controller: 'SomeController' }) 

An inline controller can be defined in the instruction via anonymous constructor.

Angular. module ('myapp', []). directive ('myctive', function () {restrict: 'A', controller: function ($ scope, $ element, $ attrs, $ transclude) {// here is the Controller logic }});

We can inject any ng service that can be injected into the controller and use it in the command. Some special services in the controller can be injected into commands. These services include:

1. $ scope

The current scope associated with the directive element.
2. $ element
The element corresponding to the current command.
3. $ attrs
An object composed of attributes of the current element.

Has the following property objects: {id: "aDiv", class: "box "}

4. $ transclude
The embedded link function is pre-bound to the corresponding embedded scope. Transclude is a function actually executed to clone elements and operate on DOM.

 angular.module('myApp',[]) .directive('myLink', function () {   return {     restrict: 'EA',     transclude: true,     controller:     function ($scope, $element,$attrs,$transclude) {       $transclude(function (clone) {                var a = angular.element('');         a.attr('href', $attrs.value);         a.text(clone.text());         $element.append(a);       });     }   }; });

Html

 
  
Baidu
 

Google

It is recommended to use transcludeFn only in the compile parameter. The link function can isolate commands from each other, while the controller defines reusable behaviors. If you want to expose the API of the current command to other commands, you can use the controller parameter. Otherwise, you can use link to construct the functionality of the current command element (internal function ). If we use scope. $ watch () or want to interact with DOM elements in real time, using the link is a better choice. With embedding, the scope in the Controller may be different from what we expect. In this case, the $ scope object cannot be properly updated. To interact with the scope on the current screen, you can use the scope parameter passed into the link function.

10. controllerAs [string]

The controllerAs parameter is used to set the alias of the controller, so that you can reference the controller in the view without injecting $ scope.

{{ main.name }}

JsCode:

 angular.module('myApp',[])  .controller('MainController', function () {    this.name = "Halower";  });

The alias of the controller makes routing and commands powerful for Creating anonymous controllers. This capability allows you to create a dynamic object as a controller, which is isolated and easy to test.

11. require [string or string []

Require represents the name of another command. Require injects the controller into the specified command and serves as the fourth parameter of the linked function of the current command. The value of a string or array element is the instruction name that will be used in the scope of the current instruction. In any case, the ng compiler will refer to the template of the current instruction when searching for the sub-controller.

If the ^ prefix is not used, the command will only search for the Controller on its own element. Command definition only searches for ng-model = "" defined in the command as the current domain ""
If you use? Prefix. If the required controller is not found in the current command, null is used as the fourth parameter passed to the link function.
If the ^ prefix is added, the command searches for the Controller specified by the require parameter in the upstream command chain.
If yes? ^ Combine the actions of the preceding two options. We can selectively load the required commands and search for them in the parent command chain.
If there is no prefix, the command will be searched in the Controller provided by itself. If no controller (or command with a specified name) is found, an error will be thrown.
12. compile [object or function]

The compile option is not frequently used, but the link function is often used. Essentially, when we set the link option, we actually created a postLink () link function so that the compile () function can define a link function. Generally, if the compile function is set, we want to perform DOM operations before the commands and real-time data are put into the DOM, it is safe to perform DOM operations such as adding and deleting nodes in this function.

The compile and link options are mutually exclusive. If both options are set, the functions returned by compile are treated as link functions, while the link options are ignored.

Compile the function to convert the template DOM. The linked function is responsible for linking the scope and DOM. You can manually operate the DOM before the scope is the same as the DOM link. In practice, this operation is rare when writing custom commands, but several built-in commands provide this function.

13. link

Compile: function (tEle, tAttrs, transcludeFn) {// todo: return function (scope, ele, attrs) {// link function };

The linked function is optional. If a compilation function is defined, it returns the linked function. Therefore, when both functions are defined, the compilation function will overload the linked function. If our commands are simple and no additional settings are required, you can return a function from the factory function (callback function) to replace the object. If this is done, this function is a link function.

14. ngModel

It provides a more underlying API to process data in the Controller. This API is used to handle data binding, verification, CSS update, and other non-actual DOM operations, the ngModel controller will be injected into the instruction along with the ngModel, which contains some methods. To access ngModelController, you must use require settings.

NgModelController has the following elements:

1) To set the view value in the scope, call the ngModel. $ setViewValue () function.
The $ setViewValue () method is suitable for listening to custom events in custom commands (for example, using jQuery plug-ins with callback functions). We want to set $ viewValue during callback and execute the digest loop.

Angular. module ('myapp'). directive ('myctive', function () {return {require :'? Ngmodel', link: function (scope, ele, attrs, ngModel) {if (! NgModel) return; $ (function () {ele. datepicker ({// callback function onSelect: function (date) {// sets the view and calls apply scope. $ apply (function () {ngModel. $ setViewValue (date );});}});});}};});

2). The $ render method can define the specific rendering mode of the view.
3). attributes (here the attributes can be learned at the end of the previous Article)

The above is all about AngularJs instructions and I hope it will be helpful for your learning.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.