Angularjs Practical Development Techniques (recommended) _angularjs

Source: Internet
Author: User
Tags html form

First, the beginning

Angular JS is a set of frames, templates, and data binding and rich UI components that are used to develop Web pages. It provides a schema for Web applications without the need for manual DOM operations. Angularjs is very small, only 60K, compatible with the mainstream browser, and jquery with good.

Ii. Basic principles of understanding

Some of ①angular's introductory knowledge

First, basic knowledge

1.angular gave up IE8.

2. The four cores are MVC, modularity, instruction system, bidirectional data binding

Ii. some of the principles

1. Do not reuse controller, a controller is generally responsible for only a small piece of view.

2. Do not manipulate the DOM inside the controller.

3. Do not contorller in the data format, Ng has a good form control.

4. Do not do data filtering operation in controller, have $filter service.

5. In general, Controller are not invoked with each other, and the interaction between the controllers is done through events.

6.angular use command to use view.

7. $scope is a tree structure, parallel to the DOM label.

8. The child $scope object inherits the properties and methods on the parent $scope.

9. Each angular application has only one $rootscope object. (generally located on Ng-app).

10. You can use Angular.element ($). Scope () for debugging.

11. Use Ngroute to route between views.

Third, the most common and practical HTML page angular built-in instructions

①.ng-class (for a similar point of praise, attention, and so on some style will change because of an operation)

The ng-class directive is used to dynamically bind one or more CSS classes to HTML elements. The value of the Ng-class directive can be a string, an object, or an array.

If it is a string, multiple class names are separated by spaces.

If it is an object, you need to use the key-value pair, the key is a Boolean value, and value is the name of the class you want to add. The class is added only if the key is true.

If it is an array, it can consist of a combination of strings or objects, and the elements of an array can be strings or objects.

Suggested two ways to use:

A, string form, the code is as follows:

<i class= "icon" ng-class= "{true: ' Ion-ios-heart ', false: ' Ion-ios-heart-outline '}[accountinfo.isfocus]" ng-click= ' Wetherfocus () ' >
</i>

This means that the I tag has a base class for icon,ng-class then binds a dynamic class, And the value of this class is determined by whether the value of Accountinfo.isfocus is true or false, and if the value is true i tag will add Ion-ios-heart This class, if the value is false I tag will be added Ion-ios-heart-outline

This class. The I tag also binds a Ng-click event that, in addition to handling the corresponding logic, determines the value of the Accountinfo.isfocus. In this case, when the Click action occurs, naturally change the I tag corresponding class, and then show a different style.

Second, the Key-value style, the code is as follows:

<i class= "icon" ng-class= "{' Ion-ios-heart ': Isios, ' Ion-android-heart ': isandroid}" > </i>

Obviously, as the code can see, the implication is that when Isios is true, the class is Ion-ios-heart, and when the Isandroid value is true, the Ion-android-heart is taken.

②.ng-show and Ng-hide (suitable for displaying two different content for different situations)

The ng-show instruction displays the specified HTML element when the expression is true, otherwise the specified HTML element is hidden.

The ng-hide instruction hides the specified HTML element when the expression is true, otherwise the specified HTML element is displayed.

Haha, watching is the brother of fire and fire ....

Examples are as follows:

<div class= "Keyboard" >
<span class= "Keyboardicon" ng-click= "Togglemenu ()" ></span>
</ div>
<div class= "Footer-menu" > <ul class= "menu-list"
ng-show= "menustate" >
...
</ul>
<div class= "footer-send" ng-hide= "menustate" >
...
</div>

Set a Boolean variable menustate (in the actual development you can use the expression, the three-mesh expression, etc.), when it is true, the contents of the Ng-show will be displayed, ng-hide content will be hidden. Vice versa ...

③.ng-switch (suitable for displaying different content in many situations)

The ng-switch instruction displays or hides the corresponding part based on an expression.

The corresponding child element uses the ng-switch-when instruction, and if the matching check selection is displayed, the other matches are removed.

By setting the default option by using the Ng-switch-default directive, the default option appears if there are no matches.

Example:

<div ng-switch= "Essaytype" >
<div class= "List-cart" ng-switch-when= "4" >
....
</div>
<div class= "List-cart left-pic" ng-switch-when= "3" >
....
</div>
<div class= "Single-pic" ng-switch-when= "1" >
...
</div>
<div class= "Single-pic" ng-switch-when= "2" >
...
</div>
<div class= "single-pic" ng-switch-default>
...
</div>
</div>

④.ng-model (Here's a little bit about Ng-model's magical pit)

The Ng-model directive binds an HTML form element into a scope variable.

If a variable does not exist in scope, it will be created. Ng-model is commonly used in <input>, <select>, <textarea> and other elements.

The following code:

<div class= "Whatisay" >
<textarea name= "my-massage-detail" Content "ng-model=" My-massage-detail "placeholder=" Please enter the message ">
</textarea>
<a class=" button btn "ng-click=" Submitmes () "> Submit </a><br></div>

By definition, it is possible, theoretically, to get the value of the Ng-model defined in the page directly in the controller when we submit it. But in practice this is not feasible. The pro-test discovery outputs a undefined and, if the initial value of Ng-model is defined in controller, the initial value is obtained rather than the updated value after the change.

Looked for some information, presumably meaning. Angular limits some of our definitions. We can only use an object that is not original to pass parameters.

What does that mean. Slightly change the above example, as follows:

HTML code:

<div class= "Whatisay" > <textarea name= "my-massage-detail" ng-model= "Model.content"
My-massage-detail "placeholder=" Please enter the message ">
</textarea>
<a class=" button btn "ng-click=" Submitmes ( ) "> Submit </a>
</div>

Controller code:

$scope. Model = {};
$scope. model.content = ';
$scope. Submitmes=function () {
console.log ($scope. model.content);
}

Is that we define an object and then define Ng-model as an attribute in this object to handle. In this way, we get the latest value of Ng-model.

There is also a relatively simple way is to directly ng-model as a parameter to pass in the good.

Examples are as follows:

HTML code
<input type= "text" ng-model= "code" >
<button ng-click= "Setcode (code)" >login</ button><br>
//controller Code
$scope. Setcode = function (code) {
alert (code);
}

Iv. practical techniques for data interaction

The use of ①promise

ES6 defines the Promise object. This object is very useful, especially when interacting with the background. It also improves the readability of the code by preventing the callback from being too deep, and by handling it in some cases. In the angularjs inside also encapsulates such a service, is $q.

$q is a service for ANGULARJS, but a simplified implementation version of the promise asynchronous programming model. The Defer object (deferred object) can be obtained by $q.defer (), which has three methods:

Resolve (Value): Sends a message to an asynchronous executor of the promise object telling him that I have successfully completed the task, value is the message sent.

Reject (value): Sends a message to an asynchronous executor of the Promise object tell him I can't finish this task, value is the message sent.

Notify (value): Sends a message to the Promise object's asynchronous executor telling him what I'm doing now, value is the message sent.

After these messages are sent, the existing callback function is invoked promise.

Promise is the commitment object with this defer object. The Promise object can be obtained by defer.promise, promise some methods of the object:

Then (successcallback,errorcallback,notifycallback): parameters are different callback functions under different messages, defer send different messages to perform different callback functions, and messages are passed as arguments to these callback functions. The return value is back to a promise object that exists to support chained calls. When the first defer object sends a message, the promise corresponding defer object also sends a message, but the message is different, regardless of whether the first defer object sends a reject or a resolve, and the second and later are sent resolve. The message is transitive.

catch (Errorcallback): abbreviation for then (null,errorcallback).

Finally (callback): equivalent to the abbreviation of then (Callback,callback), this finally method does not accept parameters, but can successfully pass the message and message type sent by defer to the next then.

Defer (): Used to generate a deferred object var defer = $q. Defer ();

Reject (): The parameter receives an error message, which is equivalent to throwing an exception in the callback function and then calling the wrong callback function in the next then.

All (): The parameter is received as a promise array, and a new single Promise object is returned, and when the Promise object corresponds to the defer object, the single Promise object is resolved, and when one of these promise objects is reject, This single promise is also reject.

When (): receives the first parameter to be an arbitrary value or is a Promise object, the other 3 then methods with promise, the return value is a Promise object. The first parameter, if not the Promise object, runs the success callback directly and the message is the object, and if promise then the return promise is actually a wrapper over the parameter of the promise type. The message sent by the promise corresponding to the defer is received by the Promise object returned by our when function.

The specific usage is as follows:

In angular, define a service that is dedicated to interaction.

Get:function (URL, options) {<br> var deferred = $q. Defer (); <br> Showtip ();
$http. Get (URL, options). Success (function (data) {
hidetip ();
if (data. Success) {
deferred.resolve (data);
} else {
deferred.reject (data). message);
}
). Error (function (data) {
hidetip ();
Deferred.reject (data);
return deferred.promise;
}
Controller inside the call get
(' url ', params)
. Then (function (data) {
//This is Successcallback
},function ( Data) {
//here is Errorcallback
});

In this way, we can define the prompts uniformly at the time each request is issued, and then hide the prompts after the request has ended. This code, presumably, means that when the request succeeds, it calls Deferred.resolve (data) and sets the state to success, which automatically executes the first function in then, Successcallback, and transfer the requested data into the database. When the request fails, the second function, the Errorcallback, is called.

The above is a small set to introduce the ANGULARJS practical development skills, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.