Angularjs Introductory Learning "instruction chapter"

Source: Internet
Author: User
Tags aliases script tag

First, we have to understand the next instruction API

Properties Meaning
Restrict Declare identifiers in the template as elements, attributes, classes, stares or combinations, how to use
Priority Set the order in which the template runs relative to other identifiers
Template Specify a string inline template, assuming you specify that the template is a URL, then it will not be used
Tempateurl Specifies the URL loaded template, assuming that you have specified an inline template string, then it will not use the
Replace Assuming true, replacing the current element, assuming false or unspecified, stitching 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 a different identifier to provide the correct function function
Link The code changes the instance of the target DOM element, joins the event listener, establishes the 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 later.


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


The Restrict:restrict property agrees to specify the declaration style for the identifier, which means it can be used as an element name, attribute, class, or gaze. We can use a string to represent each of the flags in the following table to specify

One or more declaration styles

Sign Style Demo sample
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-->


Assuming you want identifiers as elements of the latter property, you can pass the EA as a restrict string

Assuming that 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 execution, the default is zero, the normal case does not need to set the priority


Templates: When you create a component, angular agrees to replace and wrap the contents of the element in the template, assuming you want to create a label view such as the following




Instead of using a string of elements such as <div><ul><li><a>, it is possible to create an identifier <TAB-SET><TAB> by its own definition, declaring the structure of each tab individually. May assume that the next

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

At the same time, you can also use the controller for the title and the page to check the content of data binding, and use this way to make menus, accordion, pop-up, 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 template can use to set the template content,

Templateurl is used to specify which server files will be loaded, as shown in the next demo sample, we can pre-cache these templates, reduce the number of GET requests again, improve performance


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 looking at the page source code, we will still see

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


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


var appmodule = angular.module (' app ', []); Appmodule.directive (' Hello ', function () {return {restrict: ' E ', Templateurl: ' Hellotemplate.html ', replace:true};});

In hellotemplate.html, we need to write

<div> Hi there</div>

Assuming that you are using chrome, 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 via 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 see the identifier after loading, assuming you want to load the template the first time the page loads, and you can make it part of the page in the script tag, such as the following

<script type= ' text/ng-template ' 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 can be executed before the identifier executes

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 to the new template, when set to True, the identifier removes the original content and inserts it into the template again with the ng-transclude identifier

Use the transclusion method to change the Demo sample:

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

Application in:


<div hello>bob</div>

We'll see ' Hi there Bob. '




Compiling and linking functions

Although the Insert template is practical, the work that really works in whatever 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 look at a high-level view of the angular initialization process, in accordance with the order

"1" Script loading: Loading angular, finding the Ng-app identifier find app bindings

"2" compilation phase: At this stage, angular facilitates the labeling of all the symbols in the DOM logo template, transforming the DOM for each identifier, based on the rules of the identifier (template,replace,transclude, etc.), and

Assuming a compiler function exists, call it, and result in a compiled template function, which invokes all the identifiers collected by link Hansu

"3" link stage: To make the view move, angular executes 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, link stage, it processes the changes in the view of the data, along these ideas, the identifier table one function and link function is the main difference is the link function to transform the template itself, and the connection function in the model and view created dynamic link, is in the second stage, The scope scpoes is appended to the link function of the compilation process, and through data binding, the identifier becomes alive



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 from the parent class no matter what the property, when you need to isolate the operation of this identifier and the scope of the parent class, create a build can use this option


We can create these scope configurations with, for example, the following syntax classes

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

When you create a standalone scope, you cannot access the model of the parent class scope by default, but we can pass to the identifier by specifying the required 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 are able to 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 data from the parent scope, we call these data transfer methods called "Binding policy", you can specify a local alias for this property name

There are no aliases for the syntax such as the following:

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

In the form of aliases such as the following:

Scope: {attributealias: ' binding_strategy ' + ' 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 detailed sample of the changes to illustrate them, for example 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:

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

Controller code:

function Somecontroller ($scope) {$scope. title = ' Click me to expand '; $scope. Text = ' Hi there folks, I am the content+ ' tha T was hidden and is 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;}

Features of the element

Feature name
Restrict:ea Descriptive narration invokes an 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
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,
At the same time, notice that the embedded content is able to access the parent scope, not the enclosing identifier.
Scope
Link: Establish the SHOWME model, track the open and closed state of expander, and then when the user clicks on the title
Div, call the defined toggle function

Third, manipulating DOM elements

Function Descriptive narrative
Controller (name) Communicates directly with the controller, which returns the controller that is bound to the element
Assuming that this element does not exist, it iterates through the DOM and looks for recent parental controls
Alternative, assuming that the parameter name is optional and is used to specify the allowed element on 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 injection of the parent element, agreeing to find dependencies in these modules
Scope () Returns the current element or the scope of the recent parent element
Inheriteddata () Like the data () function of jquery, Inheriteddata () sets and gets the elements in a closed manner.
Data, in addition to getting data from the current element, it facilitates DOM lookups

In the following example, we do not need to ng-show and Ng-click once again to implement the Expander demo sample

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" 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 runs 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

. closed {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.