Angularjs the directive of the property meaning of the explanation

Source: Internet
Author: User

Before I introduce directive, I'd like to talk about the MVC framework. This will better understand the angular.

What is MVC? MVC is a design pattern that divides an application into three parts, a data (model), a presentation layer (view), a control interaction layer (Controller), a process that occurs at a time:

1. User and app interaction

2. The Controller's event handler is triggered

3. The controller requests the data from the model and gives it to the view

4. The view renders the data to the user.

Model

Models are used to hold all the data objects of an application, and the model does not have to know the details of the view and controller, and the model simply contains the data and the logic directly related to the data. Any event-handling code, view templates, and model-independent logic should be isolated from the model. Mixing the code of the model with the view is contrary to the MVC architecture principle. The model is the part that should be decoupled from your application.

When the controller fetches data from the server or creates a new record, it wraps the data into a model instance, that is, our data is object-oriented, and any function or logic defined on the data model can be called directly.

Therefore, do not do this:

var user = users["foo"];d estroyuser (user);

The above code has no concept of namespaces and is not object-oriented. If another destoryuser () function is defined in the application, the two functions create a conflict. We should ensure that the number of global variables and functions is as small as possible. and to do so.

var user = User.find ("foo"); User.destroy ();

In the above code, the Destory () function is stored in the instance of the namespace user. This code is clearer and very easy to inherit, and such a function like destory () does not have to be defined in every model.

View

The view layer is presented to the user, and the user interacts with it, and in JavaScript applications, the views are mostly made up of HTML, CSS, and JavaScript templates. In addition to the simple conditional statements in the template, the view should not contain any other logic.

This is not to say that MVC does not allow visual rendering-related logic, as long as this part of the logic is not defined within the view. We classify visual rendering logic as "View Helper" (helper): A separate, small tool function related to views.

The inverse--formatdate () function inserts the view directly:

template.html<div>    <script>        function formatdate (date) {/            * ... */        };    </script>    ${formatdate (this.date)}</div>

You should do this-all visual rendering logic is included in the helper variable, which is a namespace that prevents conflicts and keeps the code clear and extensible:

  

Helper.jsvar Helper = {};helper.formatdate = function () {/* ... */};//template.html<div>    ${HELPER.FORMATDA Te (this.date)}</div>

Controller

The controller is the link between the model and the view, and the controller takes time and input from the view, wakes them up (probably including the model), and corresponds to the new view. When the page loads, the controller adds event listeners to the view, such as listening for a form submission or a button click. Then, when the user interacts with the app, the event trigger in the controller begins to work.

Here's an example with jquery:

var Controller = {};//uses an anonymous function to encapsulate a scope (Controller.users = function ($) {    var nameclick = function () {/        * ... */    } ;    When the page loads, the bound event listens for    $ (function () {        $ ("#view. Name"). Click (NameClick);    });}) (JQuery);

The code above creates the users controller, which is the namespace placed under the controller variable. An anonymous function was then used to encapsulate a scope to avoid contaminating the global scope. When the page loads, the program binds the view element to the listener of the Click event.

The above is a brief introduction to MVC. The following continues with the directive properties explained.

Basically each directive is compiled by $compile, and then the link function expands the corresponding DOM element. The following describes commonly used directive-defined objects:

Priority

When more than one directive is defined on the same DOM element, it is necessary to specify the order in which the directive is applied. The priority object is usually expressed as a number, the larger the number, the corresponding designation will be first compiled, instead the directive corresponding link function will be executed more. The value of priority is assumed to be 0.

Scope (in this case, it is worth mentioning the $scope object, as well as the difference between using the $scope and this in the controller (which can be used when using controller as in HTML), and searching by itself if interested)

It has a value of three kinds; True,false (default), object.

What is scope in angular?

Scope(http://code.angularjs.org/1.0.2/docs/api/ng. $rootScope. Scope) is an object that points to the model. is also the execution context of an expression (please understand the concept of execution context yourself). Some common APIs are available in angular: $watch API (Http://code.angularjs.org/1.0.2/docs/api/ng. $rootScope. scope# $watch) for monitoring model changes , $apply API (http://code.angularjs.org/1.0.2/docs/api/ng. $rootScope. scope# $apply), which is used to monitor changes in all the model inside and outside of angular defined objects.

In angular, child scopes typically inherit the properties and methods of their parent scope through the prototype inheritance mechanism, but with one exception: in directive, use scope:{...}, the scope created in this way is a separate (isolate) scope, and it also has a parent scope, However, the parent scope is not on its prototype chain and does not inherit from the parent scope stereotype, which is typically used to construct a reusable directive component, because the defined scope does not directly access or modify the properties of the parent scope without unintended side effects.

If we access a property defined in a parent scope in a child scope, the program first looks for the property in the child scope, does not find it in the parent scope from the prototype chain, does not find it, and then looks up to the top-level prototype chain. In angular, the top of the scope prototype chain is $rootscope.

In a separate directive, the concept of scope is still relatively clear.

When scope evaluates to false, Directive does not have a separate scope object at this point, and the scope object referenced in the link function is the default controller from the current node.

When the scope evaluates to true, Directive has a separate scope object, which is inherited by the parent scope and can access all the properties in the parent scope, which is inherited by the Javasript prototype. It is important to note that when assigning a value to a property name inherited from this scope, the child scope establishes a local property corresponding to the variable property of this scope, and the properties in the parent scope are unchanged.

When the scope value is {propertyname: "[email protected]}, the directive has an isolated scope object, which is actually a new scope object, The difference from the above value is that you cannot inherit access to the properties in the parent scope through the prototype, but you can access the properties of the objects in the parent scope through the $parent property.

The following is the scope value of {...} , declare the use of the reference modifier for the scope object: (http://stackoverflow.com/questions/14050195/ Angularjs-what-is-the-difference-between-and-in-directive-scope)

1.= or =attr the properties of the isolation scope and the parent scope of the properties of the two-way binding, either side of the modification will affect the other side, at this time the attribute in the directive is the value of the corresponding $scope property on the controller, which is the most common way;

[email protected] or @attr the attribute in this directive is the literal or direct amount in HTML. This is to create a local scope property to the Dom's property binding, because the value is always string type, so this value always returns a string, and the value of the string is always inherited from the parent scope (that is, only the parent scope of the attribute values can be read, cannot be modified, belong to one-way bindings). If the property name is not specified by @attr, then the local name will be the same as the DOM property. For example <widget my-attr= "Hello {{name}}" >,widget scope is defined as: {localname: ' @myAttr '}. Then, the localname of the widget scope property maps the true value after the conversion of "Hello {{name}}". When the Name property value is changed, the LocalName property of the widget scope also changes accordingly (one-way only, unlike the "=" above). The Name property is read from the parent scope (not the component scope).

3. & or &attr the "Isolate" scope to wrap the attributes of the parent scope into a function that reads and writes the properties of the parent scope as a function, and the wrapper method is $parse ();

Controller

This is an important Property object for the interaction between nested directive.

Apply a classic definition (what the O ' reily AngularJS books by the Google Team have to say): Controller-create a Controller which publishes An API for communicating across directives. A Good example is Directive to Directive communication. It means that this controller is used to store some methods that can be shared between the various directive. When communication between two or more directive is required (that is, directive a needs to use method m in Directive B), then method m can define this method in the Controller object in Directive B. At this point, the method M is similar to some common APIs (which can be used by other Directive). For more information, please refer to: http://www.cnblogs.com/xing901022/p/4290411.html

The controller can inject the following local variables:

$scope (current element scope), $element (current Element), $attrs (the current element's attribute object), $transclude (described later in this variable, interested themselves going to Google).

Require

This object represents the need for another directive B (communication between directive) and will inject directive B's controller into the linking function, whose value is generally ' xxxcontroller ' or ' ^ Xxxcontroller ', which indicates that this directive needs to use the API in Directive B's Controller property.

Restrict

Restricting the way directive works in HTML:

The ' E ' element name, which is represented as an element in the HTML function, such as <my-directive></my-directive>

' A ' attribute, which means to function in HTML as a property, such as <div my-directive= ' exp ' ></div>

' C ' class, which means to function in HTML in the form of class, for example <div class= ' my-directive:exp; ' ></div>

' M ' functions in HTML in an annotated way, such as <!--directive:my-directive Exp--and

Of course, the above can also be used together, representing the logical and. For example restrict: ' EA ', \

Template

The template replaces the contents of an element of directive (the default), or it can be used entirely in place of the element itself (valid when the Replace value is true), or the contents of an element that encapsulates directive (valid when the value of transclude is true).

Value:

    • A string. For example <div red-on-hover>{{delete_str}}</div> .
    • A function which takes-arguments tElement and tAttrs (described in the compile function API below) and returns a string Valu E.
templateUrl

Template load address, asynchronous load.

Replace

When the value is true, the template replaces the directive element, and a value of false causes the template to replace the contents of the directive element.

Transclude

In general, there are three kinds of true, ' element ', {...}, usually used in the first two.

When the value is true, transclude the content (i.e. the child nodes) of the directive ' s element. For example:

For example, you have a statement transclude:true directive is called My-transclude-true, as follows:

<div>  <my-transclude-true>    <span>{{something}}</span>    {{otherthing}}  </my-transclude-true></div>

When it is compiled, it becomes the following:

<div>  <my-transclude-true>    <!--transcluded-  </my-transclude-true></ Div>

My-transclude-true this directive content(child node), which is ' <span>{{something. ', will be available in this directive.

For example, you have a statement transclude: ' element ' of the directive is called My-transclude-element, as follows:

<div>  <my-transclude-element>    <span>{{something}}</span>    {{otherthing}}  </my-transclude-element></div>

After being compiled, it will become as follows:

<div>   <!--transcluded--></div>

Here, the entire element of it, including its child nodes , will be available in this directive. When the transclude attribute is declared as ' element ', the template attribute in directive will lose its function.

The last important attribute: Link

This property can only be used if the compile property is undefined.

General syntax Sugar: link:function (Scope,iattrs,ielement,controller) {...}

The function of link function: Programmatically modify resulting DOM element instances, add event listeners, and set up data binding. To Program Method modifies the generated DOM element instance, adds an event listener, and sets the data binding. This is the place where the entire directive logic is put.

The following is the meaning of the parameter of this function:

Scope directive is used to register the scope of the listener event registering watches;

IElement invokes the elements of this directive instance, such as: Angular.module (' app ', []). directive (' mydirective ', function (...) {Template: ' <div data= ' data ' ><ul></ul></div> ', replace:true}); This directive element is ' <div><ul></ul></div> ', only the child node ' <ul></ul> ' that processes the element in the Postlink function is safe, because the child node has been link. (https://docs.angularjs.org/api/ng/service/$compile #link)

Iattrs invokes the attribute of the element of this directive instance, as on [data], is a collection of attribute lists.

Controller: The controller instance required by this diective is usually indicated after the Require attribute.

These are probably some of the properties that are commonly used in the development process.

The following content to be continued to predict:

1. The communication between nested directive (i.e. interaction between directive);

Data transfer and communication between 2.directive and Controller;

Data transfer and communication between the 3.controller and controller.

Angularjs the directive of the property meaning of the explanation

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.