Angularjs Learning Summary (Quick Preview)

Source: Internet
Author: User

Enhancements to HTML tags--directives

What is the nature of the instruction to invoke the corresponding script in the way it is declared, to implement some operations, where the DOM that is declared is the execution context of the script?

Custom labels--label directives
Custom Properties--Property directives
Specific format comments--Comment directives

Concept
Template View Model module directive Dependency Injection routing

> MVVM
Other MVC framework Backbone EMBERJS
Angular does not rely on any other framework
Angularjs redefined the way front-end applications are developed, and ANGULARJS is ideal for developing single-page applications (SPA)

Features of > Angularjs
1. Bidirectional data binding

2. Dom templates
In a nutshell, a template is an HTML file that contains angular directives and expressions
HTML Template---Browser parsing--->dom template---Angular compiler compilation---> Dynamic dom (bidirectional data binding)
Because it is a DOM template, angular can customize tags or attributes (directives) that have specific behavior


3. Mvc
Model
Data, is generally simple JS object

ViewModel:
is an object that provides special data and methods to maintain the specified view. ViewModel is an object of $scope and exists only in ANGUARJS applications. $scope is just a simple JS object that uses a simple API to detect and broadcast state changes.

Controller
The controller is responsible for setting the initial state and parameterized $scope method to control the behavior. The controller that needs to be noted does not save the state or interact with the remote service.

View
View is the HTML generated after parsing rendering and binding Angularjs

4. Service and Dependency Injection
Service is to provide a function of external
Built-in Di (Dependency injection) system that automatically finds and injects dependencies, facilitates development, understanding and testing

Example 1: Create a custom service and inject it into the controller
HTML Template:
<div ng-controller= "Myctrl" >
<p ng-click= "Hi (' long time no see, how is you today? ');" > Click I say hello </p>
</div>
Js:
Angular.module (' MyApp ', []). Factory (' Sayhi ', [$window, function (Win) {
return function (msg) {
Win.alert (' Hi, sindy! ' + msg);
}
}]);

function Myctrl (scope,sayhiservice) {
Scope.hi = function (msg) {
Sayhiservice.hi (msg);
};
}

Myctrl. $inject = [' $scope ', ' sayhi '];


Example 2: View-Controller-interaction of the model
...
<div ng-controller= "Democtrl" >
<input type= "text" ng-model= "User.Name" disabled= "disabled"/>
<a href= "#" ng-click= "Getajaxuser ();" >ajax Get user name </a>
</div>
...
Js:
MyModule = Angular.module (' MyApp ', []);
Mymodule.controller (' Democtrl ', function ($http, $scope) {
$scope. Getajaxuser = function () {
$http. Get (' user.php '). Success (function (data) {//ok too
$http. Get (' User.json '). Success (function (data) {
$scope. user = data;
});
};
});

5. Scope, module, controller
Scope
Both view and controller have access to the data and methods stored in the $scope, so $scope is the bridge between view and controller communication.
In the MVC architecture, the role of $scope player model is responsible for providing data and methods that are available within the scope of a DOM element.

Each angular application will have a $rootscope to the top level scope, corresponding to the DOM element that contains the Ng-app Directive attribute

Template expression {{}}

Module
var mymodule = angular.module (' MyApp ', []);

Controller
<div ng-controller= "Myctrl" >{{person.name}}</div>
The Ng-controller Directive attribute creates a $scope object for the DOM element where the outer element also has $scope objects, all $scope form the scope chain,
The child $scope object is inherited from the parent $scope in the form of a prototype, and any property and method access is found from the current $scope-No, the parent $scope is searched, and the layers are traversed up (as with the JS scope chain lookup mechanism).

Note: some directive attributes (such as: ng-repeat) can selectively create a separate scope so that the scope does not inherit its parent scope.

6. Ajax and JSONP
Use AJAX-related methods by injecting $http services, such as: $http. Get (URL). Success (FN). Error (FN);

7. Expression expressions-~ ~ Template expression?
The expression can be used as an instruction value such as: Ng-model= "Person.name" ng-click= "ShowMe ()"
Expression used in tag: {{2+3}} {{2+3|currency}}
Ng's expression cannot use loops, judge statements, use complex expressions, and try not to include logic in expressions

--all expressions are executed in the context of the current scope, so you can access the variables in the $scope
--the execution of an expression has a type error or a reference error and the error is not thrown
--Process Control statements are not allowed in expressions (If/else)
--expression can accept 1 or more series filters

8. Filter
The role of filter to format the data
{{Expresion | filter1 | Filter2 ...}} The output of the first 1 filter as input to the next filter

{{expression | filter:arg1:arg2}} filter accepts parameters

<div ng-repeat= "img in images | Filter "></div>
Use filter in JS to use it in the form of dependency injection.
Mymodule.controller (' Myctrl ', function ($scope, currencyfilter) {
$scope. num = Currencyfilter (12345);
});

Inject multiple filters
Mymodule.controller (' Myctrl ', function ($scope, $filter) {
//...
})

Ng's built-in filter:
Number, currency, date
Filter, LimitTo, lowercase, uppercse, number
JSON, by

9. Directives
There are 4 kinds of things that can be used in templates:
--directive (Directive): NG provides or customizes tags and attributes to enhance the expressiveness of HTML (~ ~ Personal understanding is to bind a certain behavior declaratively)
--Tag (markup): {{}} can bind data to a view one-way
--Filter: The output used to format the data
--form control: used to enhance the form validation function

The usage of the instructions in Ng is the largest, and Ng contains many instructions to control the template, such as Ng-repeat,ng-class, and there are many instructions to help you complete the business logic, such as Ng-controller,ng-model.
Instructions are used in several ways:

--As a label:<my-dir></my-dir> ~ ~ ~ Note that the instruction name in JS is myDir in HTML is My-dir
--as attribute: <span my-dir= "Exp" ></span>
--As an annotation:<!--directive:my-dir Exp---
--As the class name: <span class= "MY-DIR:EXP;" ></span>

In fact, it is commonly used as a label and attribute.

9.1 Style-related directives
Ng-class:
Ng-class is used to bind a class name to an element, and the return value of its expression can be in the following three ways:

--Class name string, you can split multiple class names with spaces, such as ' Redtext boldtext ';
--Class An array group, each item in the array will be stacked to take effect;
--a map with a name value that has a key value of class name, a Boolean type, and a value of true when the class is added to the element.

Ng-style:

Ng-show, Ng-hide:

9.2 Form Control-related directives
Ng-checked control the selected state of radio and checkbox
ng-selected Control Select option selected state
Ng-multiple Control Select multiple selection
Ng-disabled
Ng-readonly
Values are Boolean, valid when true; one-way binding from data to templates

9.2 Event binding-related directives
Event is a more important part of JS.
Ng-click
Ng-dblclick
Ng-change

Ng-mousedown
Ng-mouseup
Ng-mouseenter
Ng-mouseover
Ng-mousemove
Ng-mouseleave

Ng-submit


10. Special NG-SRC Ng-href
ANGULARJS parsing DOM document after domcontentloaded, so Src={{url}} href= "{{URL}}" <p>{{user.name} before domconetentloaded} </p> will appear in clear text, resulting in invalid links, template expression is not replaced by the content, the way to avoid this situation is to use NG-SRC, Ng-href, Ng-bind


<a ng-href= "url"/>

11. Custom instruction Mymodule.directrive (' UserInfo ', function () {..})

12. Services Service
A service is a singleton object or function that provides a function that is available within the module and does not pollute the global environment
System built-in services start with $


13. Routing
Angular routing mechanism is provided by the Ngroute module, through the hash and history two ways to achieve the route, the characteristics of the detection of the way to decide which route
The Ngroute module includes the following:
--$routeProvider service is used to define a routing table, which is the mapping of the address bar to the view template
--$routeParams service saved the address bar parameters such as: {id:1,name: ' Tom '}
--$route service to complete routing matching and provide routing-related services and events
The--ngview directive is used to specify the area in the main view where the child views are loaded

Above + $location service can complete a single page application (SPA)


--Introduction of JS file Angular-route.js
--injected into the controller corresponding to the root scope var mymodule = angular.module (' MyApp ', [' Ngroute ']); Node's module definition loads other dependent modules

--Define the routing table $routeProvider
When (path, route) otherwise (params)

Core method when (path, route)
* (string) path will match the $location. Path to match the parameter colon + name, such as: "/show/:name" will match the address bar/show/tom {name: ' Tome '} is saved to $routeparams, * To make a fuzzy match such as:/show*/:name will match the address bar of the/showinfo/tom

* (object) route is used to specify that some of the configuration items that are required after the path has been matched include
.. (fn|string) The controller function that the controller executes on the current template, generating a new scope
.. (string) Controlleras setting the Controller alias
.. (STRING|FN) templates used in Template view this section will be referenced by Ngview
.. (STRING|FN) Templateurl used when the view template is a separate HTML file or uses the <script type= "text/ng-template" > Define template;
.. Resolve specifies the module since the current controller
.. Redirectto REDIRECT Address

Angular animation
Through CSS3 or JS implementation, JS implementation of the bottom is through other JS library to achieve

ng animation effects include:
Animate when--enter elements are added to the DOM
--leave elements are removed from the DOM when the animation is performed
--move Animation When moving elements
--beforeaddclass
--addclass
--beforeremoveclass
--removeclass

Similar to join the routing function
First introduce angular-animate.js
Inject animation module var mymodule = angular.module (' MyApp ', [' nganimate ']);
JS Library such as JQ is introduced to realize JS animation effect.

Mymodule.animation ('. Border-animation ', function () {
return {
Beforeaddclass:function (element, className, done) {
//...
},
Removeclass:function (element, className, done) {
//...
}
}
});

-----------------------------------
Angularjs Advanced
$watch, $apply, $digest, dirty-checking

> $watch
<input name= "Txtuser" type= "text" ng-model= "user"/>
<input name= "Txtpass" type= "text" ng-model= "pass"/>
Bind the data Model $scope.user to Dom Txtuser, $scope. Pass bound to Dom Txtpass
When you bind something into the DOM, you add a $watch to the $watch team, $watch Watch for changes in the 2 things that are bound.

Every data bound to the DOM generates a $watch, and when our template is loaded, that is, in the linking phase (angular is divided into compile and linking stages), the angular interpreter looks for each directive, Then generate each required $watch.

> $digest
The browser receives an event that can be processed by the angular context, $digest will be triggered, Evalasync queue $watch queue
Traverse each $watch for dirty-checking.

If you call $apply when the event is triggered, it will go into the angular context and will not enter if no call is reached

$apply is a function of our $scope (or scope in the link function in Direcvie) that calls it to force a $digest loop (unless the loop is currently being executed, in which case an exception is thrown, which is where we do not need to execute the $ Flags of apply).

Execution $apply:
Element.bind (' click ', function () {
scope.foo++;
scope.bar++;
Scope. $apply ();
});

A better way to use $apply:
Element.bind (' click ', function () {
Scope. $apply (function () {
scope.foo++;
scope.bar++;
});
})

> Custom $watch
~ ~ ~ $watch's role is to monitor a data model (for example: $scope. Name) when it changes, the default is to synchronize the DOM with its ($scope. Name) binding, where we can customize the callback function to execute when the data model update is detected.
/*controller App.js */
App.controller (' Mainctrl ', function ($scope) {
$scope. Name = "Angular";
$scope. Updated =-1;
$scope. $watch (' name ', function () {
$scope. updated++;
});
});

/*view index.html*/
<body ng-controller= "Mainctrl" >
<input ng-model= "Name"/>
Name Updated: {{updated}} times.
</body>


Dirty-checking's execution is fast.

> Customization Instructions
Angular the HTML extension by instruction, and the enhanced HTML not only looks refreshed, but also gets a lot of powerful skills.
Angular start-up process:
Browser parsing Html=>dom--angular $compile (find template expressions and directives-associating directives to dom--multiple instructions by weight--the Complie function in the Execute instruction returns the link function) = All instructions return the LINK function queue---Execute the LINK function to connect to scope

Note here to distinguish between $compile and compile, the former is the compilation service of NG internal, the latter is the compiler function in the instruction, the two play a different range of functions.

Use and naming of instructions:
--As a label:<my-dir></my-dir>
--as attribute: <span my-dir= "Exp" ></span>
--As an annotation:<!--directive:my-dir Exp---
--As the class name: <span class= "MY-DIR:EXP;" ></span>

With regard to the naming of custom directives, you can do whatever name you like, officially it is recommended to use [namespace-directive name] in such a way as Ng-controller.
The command is named with the hump rule, use-split each word. Such as: Define mydirective, use like this:<my-directive>


Configuration parameters for custom directives:
Mymodule.directive (' Namespacedirectivename ', function (injectables) {

var directivedefinitionobject = {

How restrict:string,//instructions are used, including tags, attributes, classes, annotations

priority:number,//Priority of instruction execution

The template used by the template:string,//directive, in the form of an HTML string

templateurl:string,//loading a template from a specified URL address

replace:bool,//whether the current element is replaced with a template and, if False, append on the current element

transclude:bool,//whether to transfer the contents of the current element to the template

Scope:bool or object,//the scope of the specified instruction

Controller:function Controllerconstructor ($scope, $element, $attrs, $transclude) {...},//define interface functions to interact with other directives

require:string,//Specify additional instructions that need to be relied upon

Link:function (Scope, ielement, iattrs) {...},//programmatically manipulate the DOM, the package

Including adding listeners, etc.

Compile:function (TElement, Tattrs, transclude) {

return: {

Pre:function prelink (Scope, ielement, Iattrs, controller) {...},

Post:function Postlink (Scope, ielement, Iattrs, controller) {...}

}

}//programmatically modifies a copy of a DOM template to return a linked function

};

return directivedefinitionobject;

});

--Instruction performance configuration parameters: Restrict, template, Templateurl, replace, transclude;

--Instruction behavior configuration parameters: Compile and link;

--Instruction Partitioning scope configuration parameters: scope;

--Inter-instruction Communication configuration parameters: Controller and require.


The parsing process of the > directive:
domcontentloaded-ng Find Ng-app-Scan Instruction (directive attribute directive element interpolation directive {{}})--(according to directive configuration parameter) parse instruction for Dom (or convert to DOM) [~ ~ Generate HTML]- Sequential execution of the Complie function of each instruction (the Complie function configured when the directive is defined) accesses the DOM and operates the DOM back to the link function [~ ~ Bind the Listener]--> link function queue, enter the link stage to connect the view and scope [~ ~ Data]

If the instruction only modifies the DOM and does not bind the data, then it is configured in the Compile function, if the instruction is to be data-bound, then it is configured in the link function.


> Scoping scopes for directives using scope

As the name implies, scope is definitely a parameter related to the scope, and its role is to describe the relationship between the instruction and the parent scope, what is this parent scope? Imagine the scenario where we use the instruction, and the page structure should look like this:
<div ng-controller= "TESTC" >
<say-hello speak= "Content" > Beauty </say-hello>
</div>
The outer layer will certainly have a controller, which in the definition of controller is basically the same:
var app = Angular.module (' MyApp ', [], function () {Console.log (' here ')});
App.controller (' TESTC ', function ($scope) {
$scope. Content = ' It's a nice day today! ‘;
});

The parent scope of the so-called SayHello is the scope of the controller named TESTC, and the relationship between the instruction and the parent scope can be as follows:

False to the default value. Use the parent scope as your own scope
True to create a new scope that inherits the parent scope
JavaScript objects are isolated from the parent scope and specify variables that can be accessed from the parent scope

Scope: {
AttributeName1: ' Binding_strategy ',
AttributeName2: ' Binding_strategy ',...
}
The key is the property name and the value is the binding policy. Wait a minute! What is a binding strategy? Most hate to take a term but do not explain the behavior! Don't worry, listen to me slowly.
First say the attribute name, do you think this attributeName1 is a variable name in the parent scope? Wrong! In fact, this attribute name is a name to be used in the directive's own template, and does not correspond to the variables in the parent scope, as we will explain in a later example. Then look at the binding policy, which takes the following rules:

@ Pass a string as the value of the property str: ' @string '

= Use a property in the parent scope, bind the data to the directive's properties name: ' =username '

& Using a function in the parent scope, you can call GetName in the directive: ' &getusername '


Communication parameters between the > Instructions controller and require

It is a good idea to use directives to define a UI component, which is easy to use first, requires only a label or attribute, followed by a high reusability, the controller can dynamically control the content of the UI component, and the ability to have two-way binding. When we want to make the component a little more complex, it is not a command can be done, it requires the collaboration between instructions and instructions to complete, which requires inter-instruction communication.

Think about the principle of our modular development, a module exposed (exports) external interface, another module reference (require) it, you can use the services it provides. This is also the principle of Ng's Inter-instruction collaboration, which is the function of the controller parameters and the require parameter when customizing the instruction.

The controller parameter is used to define the interface that the directive provides externally:
Controller:function Controllerconstructor ($scope, $element, $attrs, $transclude)
It is a constructor function that, in the future, constructs an instance to be passed to the instruction that references it.
First look at the parameters that controller can use, scope, node, node properties, node content migration, which can be passed through dependency injection, so you can write only the parameters you want to use.

Look for the parent node and use it like this: require: ' ^directivename ', if not added, $compile service will only be looked up from the node itself. Alternatively, you can use the prefix:? , this prefix will tell the $compile service that if the required controller is not found, do not throw an exception.

> Performance and Tuning
Anglarjs is great, but when working with large lists that contain complex data structures, they can run very slowly
One related to the "ng-repeat" directive and the other to the filter

The ng-repeat in Angularjs will slow down when processing more than 2,500 bidirectional data bindings. This is because ANGULARJS detects changes through the "dirty checking" function. Each test takes time, so a large list with complex data structures will slow down your app.

> 7 Tuning Rules:
1. Render a list without data binding
Data binding is the most likely source of performance problems, and if you only want to display the list once, you don't need to update, change the data, and discarding data binding is a great way to go.

2. Do not calculate data using inline methods
<li ng-repeat= "item in Filtereditems ()" >//This is not a good method because it is frequently evaluated.
<li ng-repeat= "Item in Items" >//This is the method to be used

3. Use two lists (one for the view display, one as the data source)

4. Use ng-if in other templates instead of Ng-show
<div ng-if= "Item.showdetails" >
{{Item.details}}
</div>


5. Do not use Ng-mouseenter, ng-mouseleave and other instructions
Using internal directives like NG-MOUSEENTER,ANGULARJS will cause your page to blink. The browser's frame rate is typically less than 30 frames per second. Using jquery to create animations and hover effects can solve the problem. Make sure that mouse events are placed in the jquery. Live () function.

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.