ANGULARJS instruction Usage Detailed _ANGULARJS

Source: Internet
Author: User
Tags access properties event listener

This example describes the ANGULARJS instruction usage. Share to everyone for your reference, specific as follows:

Instruction (directives) is the most important ingredient in any ANGULARJS application. Although Angularjs has a lot of instructions, you often find yourself needing to create special instructions yourself. This article will take you through the custom directives and explain how to use them in real-world angular projects. At the end of the article, we'll use the angular instruction together to create a simple note-taking application.

Review

An instruction is something that introduces a new syntax. A directive is a token that is made on a DOM element and attaches some specific behavior at the same time. For example, static HTML does not know how to create and display a date selection plug-in. In order to teach HTML this new syntax we need an instruction. This command will create an element that acts as a date selector. We'll see how to implement this instruction later.

If you've already written angular apps before, then you've already used the instructions, whether you're aware of it or not. You may have used instructions such as ng-model,ng-repeat,ng-show and so on. All of these directives bind specific functions to the DOM element. For example, ng-repeat repeats a particular element, and Ng-show has a conditional display element. If you want to create a drag element, you might want to create a command. The basic idea behind the directive is simple. It makes HTML interactive by binding the event listener on the elements and transforming the DOM.

From the jquery point of view instructions

Think about how you can use jquery to create a date selector. We first add a normal input field to the HTML and then in jquery we call $ (element). Datapicker () to convert it to a date selector. But think about it. When a designer wants to check this tag, can he or she immediately guess what the field is for? Is it just a normal input field or a date selector? You have to check jquery to confirm this. The angular approach is to use instructions to extend HTML. Therefore, a date selector's instructions might look like this:

<date-picker></date-picker>

Or as shown below:

<input type= ' text ' data-picker/>

This method of creating UI components is both intuitive and clear. You can see the element and know its purpose.

Creating custom Directives

A angular directive can appear in four different forms :

1. A new HTML element (<date-picker></date-picker>)

2. Attributes on an element (<input type= ' text ' date-picker/>)

3. As a class (<input type= ' text ' class= ' Date-picker '/>)

4. As a note (<!--directive:date-picker-->)

Of course, we can definitely decide in what form our instructions appear in HTML. Now, let's take a look at how a typical angular instruction is written. It is similar to the way controller is registered, but it returns a simple object (the instruction definition), which contains attributes of some configuration directives. The following code shows a simple and hello World directive:

var app = Angular.module (' MyApp ', []);
App.directive (' HelloWorld ', function () {return
  {
    restrict: ' AE ',
    replace:true,
    Template: ' 

In the above code, the App.diretive () function registers a new instruction in our module. The first parameter of this function is the name of the instruction. The second parameter is a function that returns the instruction definition object. If your instructions are dependent on additional objects/services such as $rootScope, $http or $compile, they can also be injected into them. This instruction can be used as an HTML element, as follows:

 
 

Or:

 
 

Or as a property to use:

<div hello-world></div>

Or:

<div hello:world/>

If you want to be compatible with HTML5, you can precede the attribute with an X or data-prefix. Therefore, the following tag will match the HelloWorld directive:

<div data‐hello‐world></div>

Or

<di vx‐hello‐world></div>

Attention

When the command is matched, angular removes the prefix x or data-from the element/attribute name. Then the delimiter-or: converted to the hump notation has matched the registered instruction. That's why our HelloWorld directives are actually written in Hello-world when used in HTML.

Although the above simple instruction simply shows some static text, there are some interesting points that we should explore. We have used three attributes in this directive definition object. Let's take a look at what the three attributes are for:

Restrict -this property indicates how an instruction should be used in HTML (remember that instructions can appear in four different ways). In this example we set it to ' AE '. Therefore, this instruction can be used as an HTML element or as an attribute. To allow the instruction to be used as a class we can set restrict to ' AEC '.

Template -This practice indicates the HTML markup that is generated when the instruction is angular compiled and linked. It is not necessarily a simple string. Template can be complex, often involving other directives, expressions ({{}}), and so on. In most cases you might want to use templateurl instead of template. So ideally you should first place the template in a separate HTML file and let Templateurl point to it.

Replace -this property indicates whether the generated template replaces the element of the bound instruction. In the previous example we used the instruction in HTML to <HELLO-WORLD></HELLO-WORLD>, and set the Replace property to True. Therefore, after the instruction is compiled, the generated template replaces the

Link functions and Scopes

It is not useful to have a template generated by an instruction unless it is compiled north of the correct scope. By default, a directive does not get a new child scope. However, it can get the parent scope. This means that if an instruction is located in a controller then it will use the scope of the controller.

To take advantage of scopes, we can use a function called link. It can be configured by the link property in the instruction definition object. Now we're going to make some changes to the HelloWorld command. When a user enters a color name in an input field, the background color of the Hello wolld text changes automatically. Similarly, when a user clicks on the Hello World text, the background color is reset to white. The corresponding HTML markup looks like this:

<body ng-controller= ' Mainctrl ' >
  <input type= ' text ' ng-model= ' color ' placeholder= ' Enter a color '/>
   
 

The modified HelloWorld directive code looks like this:

App.directive (' HelloWorld ', function () {return
  {
    restrict: ' AE ',
    replace:true,
    Template: ' <p Style= "Background-color:{{color}}" ></p>,
    link:function (scope,elem,attr) {
      elem.bind (' click ', function () {
        elem.css (' background-color ', ' White ');
      Scope. $apply (function () {
        Scope.color = "white";
      });
      };
      Elem.bind (' MouseOver ', function () {
        elem.css (' cursor ', ' pointer ');
      }})
    ;


Notice that the link function is used in the directive. It receives three parameters :

Scope -it represents the scope in which the instruction is used. In the example above it is equivalent to the scope of the character controller.

Elem -it represents the Jqlite (one own) package element of the elements of the binding instruction (jquery). If you include jquery before Angularjs is included, it will become a jquery wrap element. Since the element has been jquery/jqlite wrapped, we do not need to include it in $ () for DOM operations.

Attars -it represents an attribute on the element of the binding instruction. For example, if you have some form of instruction on HTML elements:

The link function is used primarily to bind event listeners to DOM elements, monitor model property changes, and update the DOM. In the previous instruction code, we bound two listeners, click and MouseOver. The Click handler function resets the

Background color, and the mouseover handler changes the cursor to pointer. The template has the expression {{color}}, which changes the background color of the Hello World as the model color changes in the parent scope.

Compile function

The compile function is primarily used to perform some DOM transformations before the link function runs. It receives the following several parameters:

telement -an element of an instruction binding

attrs -attributes declared on an element

Note here that compile is not able to access scope and must return a link function. However, if you do not have the compile function, you can still configure the link function. The compile function can be written in the following way:

App.directive (' Test ', function () {return
  {
    compile:function (telem,attrs) {
      //here in principle do some DOM conversions
      return function (scope,elem,attrs) {
       //write Link Functions}}}}
);

Most of the time, you just need to write a link function. This is because most directives are only concerned with registering event listeners, monitors, updating the DOM, and so on, which can be done in the link function. Instructions like Ng-repeat need to clone and repeat DOM elements multiple times, and you need to use the Compile function before the link function runs. You might ask about deterrence. Use two functions separately. Why can't we just write a function? To answer this question, we need to understand how angular compiles instructions!

How the instructions are compiled

When the application is started, angular begins to parse the DOM using the $compile service. The service looks for instructions in the tag and then matches them to the registered age. Once all the instructions have been identified, angular begins to execute their compile functions. As mentioned earlier, the Compile function returns a link function that is added to the link function queue that is executed later. This is called the compile phase (compile phase). Notice that even if there are several instances of the same instruction, the compile function will only run once.

The link function is executed one by one after the compile phase, which is linked to the phase phase. In this phase the template is generated, the instruction is applied to the correct scope, and the event listener begins on the DOM element. Unlike the compile function, the Lin function executes once for each instance of the instruction.

Changing the scope of an instruction

Directives should access the parent scope by default. But we do not like to generalize about all situations. If we expose the scope of the parent controller to the instruction, then the instruction is free to modify the scope attribute. In some cases your instructions might want to add some properties and functions that only can be used internally. If we all do this in the parent scope, the parent scope may be contaminated. Therefore, we have two options:

A child scope-this scope inherits the parent scope from the prototype.

An isolated scope-a completely new, inheritable, independent scope.

Scopes can be defined by the directive definition of the scope attribute in an object. The following example shows this:

App.directive (' HelloWorld ', function () {return
  {
    scope:true,////using a self scope that inherits the parent scope
    restrict: ' AE ',
    Replace:true,
    Template: '  
 

The code above requires angular to provide an instruction with a child group that can prototype inherit the parent scope. In another case, an isolation scope, the code looks like this:

App.directive (' HelloWorld ', function () {return
  {
    scope: {},///////using a completely new isolation scope
    restrict: ' AE ',
    Replace:true,
    Template: '  
 

The instructions above use a completely new isolation scope that does not inherit the parent scope. Isolating a scope is a good choice when you want to create a reusable component. By isolating scopes We make sure that the instructions are self-contained and can be easily inserted into any HTML app. This practice prevents the parent scope from being contaminated because it is inaccessible to the parent scope. If you set scope to {} In our revised HelloWorld directive, the code will no longer function correctly. It will create an isolated scope and then the expression {{color}} will not be able to refer to the property in the isolation scope so the value becomes undefined.

Isolating scopes does not mean that you cannot get to a property in the parent scope at all. There are techniques that allow you to access properties in the parent scope and listen for changes to these properties simultaneously. We will mention this advanced technique in subsequent articles.

I hope this article will help you to Angularjs program design.

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.