Angularjs Introductory Learning "instruction chapter"

Source: Internet
Author: User

Original http://blog.csdn.net/xpf_show/article/details/36233465

First, we have to understand the next instruction API

Meaning
Restrict Declare identifiers in the template as elements, attributes, classes, comments or combinations, how to use
Priority To set the order of execution in a template relative to other identifiers
Template Specify a string inline template, if you specify a template is a URL, then it will not be used
Tempateurl Specifies the URL-loaded template, if you have specified an inline template string, it will not use the
Replace If true, replaces the current element if it is false or unspecified, stitching it to the current element
Transclude Move the original byte of an identifier take you to the location of a new template
Scope Create a new scope for this identifier, rather than inheriting the parent scope
Controller Create a controller to expose the communication API through identifiers
Require The current identifier requires an additional identifier to provide the correct function function
Link Modify the instance of the target DOM element by code, add event listener, establish data binding
Compile modifying DOM templates with identifier copy programming

Here, we simply understand the meaning of each attribute and its simple role, and we'll explain it in a few inspirational words.

Next, let's take a look at the instruction definition object

The Restrict:restrict property allows you to specify a declaration style for an identifier, which means it can be an element name, attribute, class, or comment. We can use a string to represent each flag in the following table to specify

One or more declaration styles

Sign Style Example
E Element <my-menu title= ' Products ' ></my-menu>
A Attribute <div my-menu= ' Products ' ></div>
C Class <div class= ' my-menu:products ' ></div>
M Comment <!--Directive:my-menu products-->

If you want identifiers as elements of the latter attribute, you can pass the EA as a restrict string

If the Restrict attribute is omitted, the default is a, see the angular document for details

Priorities: Specifies the order for the application, the higher the value, the first to run, the default is zero, and in general, no priority needs to be set

Templates: When you create a component, angular allows you to replace and wrap the contents of the element in the template, if you want to create a label view like this

Instead of using a string of elements such as <div><ul><li><a>, you can create identifiers <tab-set><tab> by customizing them, declaring the structure of each tab individually. Maybe if the next

<tab-set><title=' Home ' ><p>welcome home!  </p></tab><title=' Preferences ' ><!--Preferences UI goes Here--</tab></tabset>        

At the same time, you can also use the controller for the title and tab content data binding, and in this way to make menus, accordion, pop windows, dialog boxes or other application requirements

Next, let's take a look at the temp lvl or the Templateurl property, specifying the replacement DOM element. In the table above, we see a string that the template can use to set the template content.

Templateurl is used to specify the server files that will be loaded, as shown in the next example, we can pre-cache these templates, reduce the number of get requests over and over again, improve performance

<lang=ng-app=' app ' ... <body><hello></hello></body>     

Create

var appmodule = angular.module (' app ', []); Appmodule.directive (' Hello ', function () {return {restrict: ' E ', Template: '  <Div>hi there</div> ', replace:true};});   

After loading into the browser, we will see hi there, by viewing the page source, we will still see

<body><div>hi there</div>    </body> 

Rather than using the template to input HTML into the string is not very meaningful, we will generally use Templateurl, to set the appropriate head cache

var appmodule = angular.module (' app ', []); Appmodule.directive (function () {true};});  

In hellotemplate.html, we need to write

<div> Hi there</div>  

If you use a Chrome browser, the same-origin policy may cause an error "origin null is not a allowed by Access-controll-allow-origin". Here you have two options.

1. Loading apps from the server

Set a flag in 2.chrome to resolve by command line ' Chrome-allow-file-access-from-files '

Then loading the file via Templateurl will cause the user to wait to know when the load is seen, and if you want to load the template the first time the page loads, you can make it part of the page in the Script tab, as follows

<type=id=' hellotemplateinline.html ' ><div>hi there</div></  script>     

The id attribute here is very important, because is the URL key, angular uses it to save the template, you should use the ID in the identifier's templateurl to specify insert that template

And we can load the template through $http or several other mechanisms, and then set it directly to the $templatecache object used by angular, and call it through the run function so that the template will be in

Available in cache

var appmodule = angular.module (' app ', []); Appmodule.run (function ($templateCache) {$templateCache. put (' Hellotemplatecached.html ', '<div>hi there</div> '); Appmodule.directive (' Hello ', function () {return {restrict: ' E ', Templateurl: ' hellotemplatecached.html ', replace:true };});

Transclusion (embedding included)

Moving the original content through the Transclude property into the new template, when set to True, the identifier removes the original content and inserts it back into the template with the ng-transclude identifier

To modify an example by using transclusion mode:

Appmodule.directive (' Hello ', function () {return {Template: '<<ng-transclude></span ></div> ', transclude:true};});      

Application in:

<Hello>bob</div>  

We'll see ' Hi there Bob. '

Compiling and linking functions

Although the Insert template is useful, the real meaningful work in any identifier happens in the Compile live link function

The function of compiling and linking is angular the latter two stages of creating a live view for a reference, so let's take a look at a high-level view of the angular initialization process, in order

"1" Script load: Load angular, find Ng-app identifier find app bindings

"2" compilation phase: At this stage, angular facilitates all registered flags in the DOM logo template, for each identifier, based on the rules of the identifier (Template,replace,transclude, etc.) to transform the DOM, and then

If a compiler function exists, it is called, resulting in a compiled template function, which invokes all identifiers collected by link Hansu

"3" link stage: In order for the view to move, angular runs the link function for each identifier, and the link function typically creates listeners on the DOM or model that keep the view and model consistently

So at the compile stage, it handles the transformation of the template, the link stage, which handles the modification of the data in the view, along these lines, the main difference between the table one function and the link function in the identifier is that the link function transforms the template itself, and the connection function creates a dynamic link on the model and view, in the second stage, The scope scpoes is appended to the link function of the compilation process, and the identifier becomes alive through data binding.

Second, scope

Three options for getting scope scope

1. Scopes that already exist in the identifier DOM element

2, create a new scope that inherits the enclosing controller scope to read all the values of the tree scope.

3. Independent action, do not inherit any attributes from the parent class, when you need to isolate the operation of this identifier and the scope of the parent class, create a build that can be used to use this option

We can create these scope configurations with the following syntax classes

Existing scopes Scope:false (This is the default value if not specified)
New Scope Scope:true
Independent scopes scope:{attribute rank and binding style}

When you create a standalone scope, the model of the parent class scope cannot be accessed by default, but we can pass to the identifier by specifying the desired property

Note: Although independent scopes do not inherit model properties, they are still child nodes of the parent scope and $parent point to the parent class

We can pass the specified property to the parent class through the key value of the identifier property to the independent scope, there are three ways to pass the data from the parent scope, we call these data transfer methods called "Binding policy", you can specify a local alias for this property name

The syntax without aliases is as follows:

Scope: {attributeName1: ' Binding_strategy ', attributeName2: ' Binding_strategy ', ...}

The format for aliases is as follows:

Attributealias:' templateattributename ',...}
Symbol Significance
@ Passing string properties, you can bind data from a chalk scope by using the override {{}} property value
= Data binding properties in the attribute of the parent scope of the identifier
& Passes a function from the parent scope, which is called later

Here we use a specific example of the changes to illustrate them, such as we want to create a expander identifier, display a title bar, when clicked to expand the display of additional content

When it's closed.

State of Open

The code is as follows:

<ng-controller= 'somecontroller ' ><class=expander-title=' title ' >{{text}} </expander></div>         

Controller code:

Somecontroller($scope) {' Click me to expand ';' Hi there folks, I am the content+ ' that were hidden but are now shown. ';}    

Then we write the identifier

Angular.module (' Expandermodule ', []). directive (' Expander ', function () {return {restrict: ' EA ', replace:true, Transclude:true,scope: {title: ' =expandertitle '}, Template: '<div> ' + '<div class="title" ng-click="toggle ()" >{{title}}</ div> ' + '<div class="Body" ng-show="showMe" ng-transclude>< /div> ' + '</div> ', link:function (scope, element, attrs) {scope.showme = False;scope.toggle = function Toggle () {scope.showme =!scope.showme;}}});           

Style:

. Expander{Border 1px solid black;Width 250px;} . Expander > . title {background-color: black;  Color: white ; padding: .  1em. 3em; cursor: pointer;} . Expander > . Body {padding: .  1em. 3em; }< /c5> 

Features of the element

Feature name
Restrict:ea Describes the invocation identifier as an element or attribute, i.e. <expander> </expander> or <div expander>...</div>
Replace:true Replace the original element with the provided template
Transclude:true Move the original element content to another place in the provided template
Scope:{title:=expandertitle}} Creates a local scope property called title, which is used to bind data to Expander-title
The Parent-scope attribute declared in the property, here, for the convenience of Expandertitle to name
For title, because Expandertitle in the template, we bleed the scope of blood
Scope:{expandertitle: ' = '} to reference it, but in this scenario, the other identifiers are also
There is a title property, in order to prevent ambiguity, we rename it
template:<div>+ Provide an upcoming template for identifiers, note that we use Ng-click and ng-show
To show or hide itself, ng-transclude to affirm where the original content will go,
Also note that embedded content can access the parent scope, not the enclosing identifier.
Scope
Link: Establish the SHOWME model, track the open and closed state of expander, and then invoke the defined toggle function when the user taps the title div

Third, manipulating DOM elements

Function Describe
Controller (name) Communicates directly with the controller, which returns the controller that is bound to the element
If this element does not exist, it will traverse the DOM and then find the nearest parent control
If the parameter name is optional, it is used to specify the consent element on the other
Identifier name, if provided, returns the controller on the identifier, the name
Should use hump, that is to say, replace Ng-model with Ngmodel
Injector () Gets the current element or the injector of the parent element, allowing the lookup of dependencies in these modules
Scope () Returns the current element or the scope of the nearest parent element
Inheriteddata () Like the jquery data () function, Inheriteddata () sets and gets the data on the element in a closed manner, in addition to fetching the data from the current element, which facilitates DOM lookups

In the following example, we do not need to ng-show and Ng-click to re-implement the previous expander example

Angular.module (' Expandermodule ', []). directive (' Expander ', function () {return {restrict: ' EA ', replace:true, Transclude:true,scope: {title: ' =expandertitle '}, Template: '<div> ' + ' <div class=" title ">{{title}}</div> ' + ' <div class= "body Closed" span class= "attribute" >ng-transclude></div> ' + '  </div> ', link:function (scope, element, attrs) {var titleelement = angular.element ( Element.children (). EQ (0)), var bodyelement = Angular.element (Element.children (). EQ (1)); Titleelement.bind (' Click ', Toggle); function Toggle () {bodyelement.toggleclass (' closed ');}}});        

In the above we remove the Ng-click and ng-show identifiers from the template, however, when the user clicks on the expander header and still performs the expected action, we create a jqlite element from the tittle element, Then bind the toggle function to the Click event as its callback, in the toggle function, we call Toggleclass () on the expander BODY element

To add or remove closed classes, we will set this element class to Displat:none

{display: none;}  

Angularjs Introductory Learning "instruction chapter"

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.