Instruction Practice Development Guide in Angularjs (i) _angularjs

Source: Internet
Author: User
Tags event listener html tags

Instruction (directives) is the most important part of all ANGULARJS applications. Although Angularjs has provided very rich instructions, it is often necessary to create application-specific directives. This tutorial will tell you how to customize instructions and how to use them in real projects. At the end of this article (Part II), I'll instruct you on how to use the angular directive to create a simple Notepad application.

Overview

A directive is used to introduce new HTML syntax. An instruction is a token on a DOM element that has a specific behavior for that element. For example, static HTML does not know how to create and present a date selector control. To allow HTML to recognize this syntax, we need to use instructions. Directives can be used to create an element that supports date selection. We will introduce step-by-step how this is achieved. If you have written ANGULARJS applications, then you must have used the instructions, whether you realize it or not. You must have used simple instructions, such as Ng-mode, Ng-repeat, ng-show, etc. These directives give DOM element-specific behavior. For example, ng-repeat repeats a particular element, Ng-show conditionally displays an element. If you want an element to support dragging, you also need to create a command to implement it. The basic idea behind the directive is simple. It enables HTML to have real interactivity by listening to the element binding events or changing the DOM.

jquery Perspective

Imagine using jquery to create a date selector. First, we add an ordinary input box to the HTML and then call $ (element) through jquery. Datapicker () to convert it into a date selector. But think about it. When a designer comes to check the HTML tag, can he or she immediately guess what the field actually represents? Is this just a simple input box, or a date selector? You need to look at the jquery code to determine this. The angular approach is to use a single instruction to extend the HTML. So, a date selector's instruction can be in the following form:

<input type= "Text"/>

Or is this:

<input type= "Text"/>

This is a much more straightforward and clear way to create a UI build. You can easily see what this is all about by looking at the elements.

To create a custom directive:

A angular instruction can have the following four representations: 1. A new HTML Element (<data-picker></data-picker>) 2. The attributes of the element (<input type= "text" data-picker/>) 3. CSS Class (<input type= "text" class= "Data-picker"/>) 4. Note (<!–directive:data-picker–>) Of course, we can control the representation of our instructions in HTML. Now let's take a look at a typical instruction in Angularjs. The instructions are registered in the same way as controller, but it returns a simple object (instruction definition object) that has the command configuration attribute. The following code is a simple Hello world directive.

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

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

 
 

Or, use it as a property:

<div hello-world></div>
//or
<div hello:world/>

If you want to conform to the HTML5 specification, you can add an X or data-prefix to the element before it. So the following tag will also match the HelloWorld directive:

<div data-hello-world></div>
//or
<div x-hello-world></div>

Note: When matching instructions, angular will remove the X-or data-prefixes in the name of the element or attribute. The-or: concatenated strings are then converted to hump (CamelCase) representations, which are then matched with registered instructions. This is why we use the helloWorld instruction in HTML in Hello-world way. In fact, this is related to HTML's case-insensitive for tags and attributes. Although the above instructions only achieve static text display, but here are some interesting points worth digging. We used three attributes to configure instructions during the instruction definition process. Let's explain their role.

restrict– This property is used to specify how instructions are used in HTML (remember the four representations of instructions that were previously said). In the example above, we used the ' AE '. So this instruction can be used as a new HTML element or attribute. If you want to allow instructions to be used as class, we set the restrict to ' AEC '.

template– This property sets the HTML markup that is generated after the instruction is angular compiled and linked (link). This attribute value is not necessarily a simple string. Template can be very complex and often contain other directives, as well as expressions ({{}}). More often than not, you may see templateurl instead of template. So ideally, you should put the template in a particular HTML file, and then point the Templateurl attribute to it.
Replace– This property indicates whether the generated HTML content will replace the HTML element that defines this directive. In our example, we use our instructions in the Open this plunker, in "Hello world!!" Right-click the element content to understand this more vividly.

Link functions and scope

The template generated by the directive does not have much meaning unless it is compiled under a specific scope. By default, the directive does not create a new child scope. More, it uses the parent scope. In other words, if the instruction exists under a controller, it will use the scope of the controller. How to use scope, we need to use a function called link. It is configured by the directive to define the link property in the object. Let's change our HelloWorld instructions, when the user enters a name for a color in an input box, the background color of the Hello world text changes automatically. Also, when the user clicks on the Hello World text, the background color changes back to white. The corresponding HTML tags are as follows:

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

The revised HelloWorld instructions are as follows:

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

We note the LINK function in the directive definition. It has three parameters:

Scope of the scope– directive. In our case, the scope of the instruction is the scope of the parent controller.
The Jqlite (subset of jquery) of the elem– directive wraps the DOM element. If you introduced jquery before introducing Angularjs, then this element is the jquery element, not the jqlite element. Since this element has been jquery/jqlite packaged, we do not need to use $ () to wrap the DOM operation.
attr– a normalized parameter object that contains the attributes of the element on which the instruction resides. For example, you add attributes to an HTML element: You can use it through Attrs.someattribute in the link function.

The link function is used primarily to add event sniffing to DOM elements, monitor model property changes, and update the DOM. In the instruction code snippet above, we added two events, click, and MouseOver. The click handler functions to reset the <p> background color, while the mouseover handler changes the mouse to pointer. There is an expression {{color}} in the template that is used to change the background color of the Hello world text when the color in the parent scope changes. This plunker demonstrates these concepts.

Compile function

The compile function is used to make some DOM modifications before the link function is executed. It receives the following parameters:

The element where the telement– directive is located
Standardized list of parameters given on the attrs– element
Note that the compile function does not have access to scope and must return a link function. However, if you do not set the compile function, you can configure the link function properly (with compile, you cannot return it by compile with the Link,link function). The compile function can be written in the following form:

App.directive (' Test ', function () {return
{
compile:function (telem,attrs) {
//do optional DOM Transformation here return
function (scope,elem,attrs) {
//linking function here
}
;}};

In most cases, you just need to use the link function. This is because most of the instructions only need to consider registering the event listener, monitoring the model, and updating the DOM, which can be done in the link function. However, for instructions like ng-repeat, you need to clone and repeat DOM elements multiple times, which are done by the compile function before the link function executes. This brings up a problem, why we need two separate functions to complete the build process, why not just use one? To answer this question, we need to understand how the instructions are compiled in the angular!

How the instructions are compiled

When the application boot starts, angular begins to traverse the DOM element using the $compile service. This service searches for instructions in tagged text based on registered directives. Once all the instructions have been identified, the angular executes their compile method. As mentioned earlier, the Compile method returns a link function that is added to the list of link functions that will be executed later. This is called the compile phase. If a command needs to be cloned many times (such as Ng-repeat), the compile function is executed only once in the compile phase, but the link function is executed for each replicated instance. So separate processing, let us have a certain improvement in performance. This also explains why the scope object cannot be accessed in the compile function. After the compile phase, the link (linking) phase begins. At this stage, all the collected link functions will be executed by one by one. The template created by the directive is parsed and processed under the correct scope, and then returns the true DOM node with the event response.

Change the scope of the instruction

By default, the instruction acquires the scope of the controller of its parent node. But that does not apply in all cases. If the scope of the parent controller is exposed to instructions, they are free to modify the properties of the scope. In some cases, your instructions would like to be able to add some properties and methods that are limited to internal use. If we add to the scope of the parent, the parent scope is contaminated. In fact, we still have two options:

A child scope– This scope prototype inherits the child parent scope.
An isolated scope– exists that does not inherit from the scope of the parent scope.
Such a scope can be configured by the directive to define the scope property in the object. The following code fragment is an example:

App.directive (' HelloWorld ', function () {return
{
scope:true, 
//Use a child scope that inherits from parent< C6/>restrict: ' AE ',
replace: ' true ',
Template: '  
 

The above code, let angular create a new child scope that inherits from the parent SOCPE to the instruction. Another option, the scope of the isolation:

App.directive (' HelloWorld ', function () {return
{
scope: {}, 
//] Use a new isolated scope
restrict: ' AE ',
replace: ' true ',
Template: '  
 

This directive uses an isolated scope. The scope of isolation is very beneficial when we want to create reusable instructions. By using the isolation scope, we are able to ensure that our instructions are self-contained and can be easily inserted into HTML applications. It does not have access to the scope of the parent, which ensures that the parent scope is not contaminated. In our HelloWorld instruction example, if we set scope to {}, the above code will not work. It creates a new quarantine scope, the corresponding expression {{color}} will point to this new scope, and its value will be undefined. Using the scope of isolation does not mean that we cannot access the properties of the parent scope at all. There are some techniques that allow us to access the properties of the parent scope and even monitor their changes. We will discuss these techniques in the second part of the instruction series, as well as some of the more advanced concepts, such as the Controller function. The second part will also work with you to create a richer Notepad application using the angular directive.

About the instructions in the Angularjs Practice Guide (a), small series to introduce to you here, the following article to introduce ANGULARJS instructions in the practice of the Development Guide two (ii), I hope to help you!

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.