AngularJS Lecture, four Directive

Source: Internet
Author: User

AngularJS Directive Custom directive (one of my favorite features of AngularJS)

A: When will we use the directive?

1. Make the HTML more semantic, without having to delve into the logic of the research code to know the approximate logic.

2. Abstract a custom component that can be reused.

Two: the definition of directive and its use method

1. Below is a directive parameter detail template

Angular.module (' app ', []);//Declare a call to Angularjs block   angular.module (' app '). Directive (' directivename ', function Factory () {    var directivedefinitionobject = {  
Restrict: ' A ', Template: ' <div></div> ', templateurl: ' directive.html ', Replace:false, Tran      Sclude:false, scope:false, compile:function compile (telement, Tattrs, transclude) { return { Pre:function prelink (Scope, ielement, Iattrs, controller) {...}, post:function postlink (Scope, ielement     , Iattrs, controller) {...} }}, link:function postlink (scope, ielement, Iattrs) {...}};

2. Detailed parameters

Priority

(number), optional parameter, indicating the priority of the instruction, if there is more than one instruction on a single DOM, the priority is high first execution;

Terminal

(Boolean), optional parameter, true or FALSE, if set to true, other instructions with a lower priority than this instruction are not valid and are not invoked (the same priority or execution);

Restrict

(string) optional parameter that indicates in what form the instruction is declared in the DOM;

The values are: E (Element), a (attribute), C (Class), M (note), where the default value is a; Of course it can be used together, such as an EA. indicates that either an element or an attribute can be.

E (Element):<directivename></directivename>
A (attribute): <div directivename= ' expression ' ></div>
C (Class): <div class= ' directivename ' ></div>
M (note): <--directive:directivename expression-->
In general, E/A/C used more.

Template

(string or function), optional parameter

Example: (1) when the string:

<! DOCTYPE html> 

(2) Function: There are two parameters telement and Tattrs

TElement: An element that uses this directive

Tattrs: The attributes on the directive element

<! DOCTYPE html> 

Templateurl:

(string or function) optional parameter

String: A string representing the path of the HTML file

Function: Can receive two parameters telement and Tattrs (roughly ibid.)

(PS: Because loading the HTML template is loaded asynchronously, if loading a large number of templates will slow down the speed of the site, so we can cache the template first)

Example: (Load the page first to be included in the HTML you need)

<! DOCTYPE html> 

There is another way:

Angular.module ("App"). Run (["$templateCache", function ($templateCache) {  $templateCache. Put ("hello.html",  

Replace

(boolean value): The default value is False. true: Replace instruction (

Transclude: (Whether you want the content inside the instruction to be replaced by the template)

(boolean value): The default value is False. True: Need to be used with NG transclude

Example: Template: "<div>hello every <div ng-transclude></div></div>"

In this case, the content inside the instruction is embedded in the ng-transclude Div. It becomes the <div>hello every <div> this is the content </div></div> within the directive.

Scope

1) The default value is False. Represents an inherited parent scope; (inheritance is not isolated)

2) True. Represents an inherited parent scope and creates its own scope (child scope);(inheritance isolation)

3) {}. Represents the creation of a completely new isolation scope; (does not inherit isolation)

(PS: The isolation scope is a good choice when you want to create a reusable component, by isolating the scope we ensure that the directive is ' independent ' and can be easily inserted into any HTML app, and this practice prevents the parent scope from being contaminated;)

The following is a detailed explanation of the isolation scope:

A. How the isolation scope accesses the parent scope:

Directive provides three ways to interact with areas outside of isolation when using isolation scopes.

1). @

(Used to access a string value defined by the directive external environment, primarily by binding an external string value through the Tag property where directive is located.) This binding is unidirectional, that is, the binding change of the parent scope, the properties of scope in directive are synchronized, and the binding changes in the isolation scope are not known to the parent scope. PS: equivalent to inheritance isolation

scope:{

Name: "@"

}

2). &

(& provides a way for a directive to execute an expression in the context of the parent scope.) When there are actions in Directive that need to be updated in the parent scope, you can execute a piece of code or a function in the context of the parent scope. PS: That is, binding is the method)

        

<! DOCTYPE html> 

3). =

(The value of the Attr property of Directive establishes a two-way binding between the local scope property and the parent scope property name.)
This means that when you want a property with a two-way binding, you can use = to introduce an external property. Both parent scope and Quarantine scope Update property values at the same time, either by changing the parent scope or by isolating the properties in scope, because they are two-way bound relationships. )

Cases:

<! DOCTYPE html> 

Controller

(Can be a string or function)

    

In addition, there are special services (parameters) that can be injected

(1) $scope, the scope associated with the instruction element

(2) $element, the element corresponding to the current instruction

(3) $attrs, an object consisting of the attributes of the current element

(4) $transclude, embedded link function, actually executed to clone the element and manipulate the DOM function

Note: unless it is used to define some reusable behavior, it is generally not recommended to use it here.
The controller of the instruction and the link function (which is said later) can be interchanged. The difference is that the controller is primarily used to provide the behavior that can be reused between instructions, but the link linkage function can only define the behavior in the current internal instruction and can no longer be reused between instructions.

   

<! DOCTYPE html> 

Here if we want a useful parent scope: $scope. $parent

New scope: $scope. $parent. New ()

Controlleras

Set the alias of the controller (angular1.2 brings us the new syntax sugar)

Cases:

<script>  angular.module (' app ', []). directive (' mydirective ', function () {  return {   restrict: ' EA ',   Transclude:true,   controller: ' Somecontroller ',   controlleras: ' Maincontroller '  //. Other configuration  };  });  

Require

String or array

The string represents the name of another instruction as the fourth parameter of the link function. Let's say now we're going to write two instructions, and there are a lot of coincident methods in the link function in the two instructions. At this point we can write these repeated methods in the controller of the third instruction (also mentioned above that the controller is often used to provide multiplexing between instructions) and then in these two instructions, require the command with the Controller field (the third command) , you can refer to these coincident methods at the end of the fourth parameter of the link linking function.

Example

<!doctype html> 

There are four types of require parameters:

1) without a prefix, the instruction will be found in the controller provided by itself, and if no controller is found, an error will be thrown

2)? If the required controller is not found in the current instruction, NULL is passed to the fourth parameter of the link connection function

3) ^ If the required controller is not found in the current instruction, the controller of the parent element will be looked up

4)? ^ combination

Compile function

function compile (telement, Tattrs, transclude) {...}

The compiler function is used to modify the template Dom (infrequently used)

You need to use a compile function such as: Ngtrepeat;ngview (you need to load the content asynchronously).

The meaning of each parameter:

Telement-template element that contains the directive.

Tattrs-template the attributes declared on the attributes directive element.

transclude-an embedded link function functions (scope, CLONELINKINGFN).

Note: Do not perform any operations outside of the DOM transformation in the compilation function. More importantly, the registration of DOM listener events should be done in the link function, not in the compilation function. A compilation function can return an object or function. The return function-is equivalent to the link function registered with the Link property of the configuration object when the compilation function does not exist. Return object-Returns an object that has registered a function through the pre or post property. Refer to the explanations below for the pre-linking and post-liking functions.

Link function

function link (scope, ielement, Iattrs, controller) {...}
The link function is responsible for registering DOM events and updating the DOM. It is executed after the template has been cloned, and it is also where most of the instruction logic code is written.
Scope-the scope in which the instruction needs to be monitored.
ielement-instance element-The elements in which the directive resides. It is only safe to operate on the child elements of the element in the Postlink function, because they are all linked well at that time.
Iattrs-instance attributes-instance properties, a normalized, all attribute list declared on the current element, which is shared across all linked functions.
Controller-An instance of the director, which is the current instruction somedirective the internal controller through the instruction of the require request. For example: Controller:function () {This) in the somedirective directive. Say = function () {}}, then, in the link function of the current instruction, you can pass the controller. The say is called.
The Pre-linking function executes before the child element is linked. cannot be used to deform the DOM in case the link function cannot find the correct element to link to.
post-linking function all elements are linked and executed.

Compile function and link functions need to be noted: The two are mutually exclusive, compile function is responsible for modifying the template DOM, link function is responsible for the scope and the DOM to connect.

When the two coexist, the functions returned by the compile function are ignored as link function,link.

  

    

 

  

  

  

    

AngularJS Lecture, four Directive

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.