A partial summary of ANGULARJS

Source: Internet
Author: User
Tags call back

Just this week, we learned a magical framework called: "Angular js", its magic is not how strong its function, even its function is very simple, but its kind of thought is very good; he completely abandoned what we are used to now. Get the object first, The object is then bound or disposed of. It completely gives up the DOM operation and makes it simple. But what we are talking about is good, there will be undesirable places, for example, its adaptability is not very good, need a lot of Dom operation, it is not the use of it, such as the game, And because it is contrary to our conventional practice, it is not very friendly for beginners, some people say it is very cool, and some people say I am not used to it.

Here is a piece of code, basically I did not write, the following is the code involved:

<script type= "text/javascript" src= "//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" ></script> <div data-ng-app>      单价: <input type= "number" min=0 ng-model= "price" ng-init= "price = 299" >      <br>      数量: <input type= "number" min=0 ng-model= "quantity" ng-init= "quantity = 1" >      <br>      总价: {{ quantity * price }} </div>We can see that to realize the above function is two input box, the input number multiplied, to get the results, with ordinary JS or jquery will write a lot of JS code, with this angularjs will not be many; But without a silver bullet, like any other frame, AngularJS has its limitations. CRUD type of operation is what it is good at, think about the previous written management background, almost most of the data is read from the database, and then presented on the page, for various additions and deletions to change. AngularJS agreed on a set of specifications, so you can easily manipulate the data.  In other ways, such as the development of complex Web games, AngularJS is useless. First, some characteristics of AngularJS and problems needing attention two-way binding

As the above example shows, we can write expressions in HTML like PHP Smarty templates, wrapping them with {{and}}. In AngularJS, the view and Model are bound in the controller, so whether you modify the content in the view's form or modify the Model value through the code in the controller, both sides will change instantly and synchronize updates. Because the AngularJS monitors the changes of the Model object, it is always reflected in the View.

In this case, we have learned that he is strong;

Because of the habit of writing JavaScript in the past, it is easy to fall into some AngularJS traps. The following assumes that you already know the concept of front-end MVC and have some experience with AngularJS, and beginners may read it more obscures.

DOM operations

Avoid using JQuery to manipulate the DOM, including adding element nodes, removing element nodes, getting element content, hiding or displaying elements. You should use directives to implement these actions, and if necessary, write your own directives.

If you find it hard to change your habits, consider removing jQuery from your Web page. Really, the service in AngularJS $http is very powerful, basically can replace the Ajax function of jquery, and AngularJS embedded jqlite--its internal implementation of a jquery subset, including the common jquery DOM operation method, Event bindings, and so on. But this is not to say that using ANGULARJS can not use JQuery. If your page is loaded with jquery then AngularJS will take precedence over your jquery, otherwise it will fall back to Jqlite.

The situation where you need to write your own directives is usually when you use a third-party jQuery plugin. Because the plug-in changes the form value outside of AngularJS, it does not immediately react to the Model. For example, we use more jQueryUI DatePicker plug-ins, when you select a date, the plugin will fill the date string into the input box. The View changed, but did not update the Model, because $(‘.datepicker‘).datepicker(); this code does not belong to the AngularJS management scope. We need to write a directive to get the DOM changes to be updated in the Model immediately.

?
123456789101112131415 var directives = angular.module(‘directives‘, []); directives.directive(‘datepicker‘, function() {   return function(scope, element, attrs) {       element.datepicker({           inline: true,           dateFormat: ‘dd.mm.yy‘,           onSelect: function(dateText) {               var modelPath = $(this).attr(‘ng-model‘);               putObject(modelPath, scope, dateText);               scope.$apply();           }       });   }});

and introduce this direcitve in HTML.

?
1 <input type="text"datepicker ng-model="myObject.myDateValue"/>

  

Plainly directive is in the HTML to write custom tag attributes, to achieve the role of plug-ins. This declarative syntax extends the HTML.

It is important to note that there is a Angularui project that provides a lot of directive for us to use, including plugins in the Bootstrap framework and other popular UI components based on jQuery. As I said before, the AngularJS community is very active and the ecosystem is sound.

Value in the Ngoption

It's a big hole. If you go to view <select> the option values in the ngoption generated <option> (each <option value="xxx"> of the value parts), that is definitely vain. Because the value here will always be the index of the inner element of the AngularJS, not the form option value you specified.

Or to change the concept, AngularJS is no longer using forms to interact with the data, but with Model. Use the $http to submit the Model, which is used in PHP file_get_contents(‘php://input‘) to get the data submitted by the front end.

Problem with {{}}

When the page is initialized, the user may see {{}} and then flash before the real content appears. Workaround:

    1. Use ng-cloak directive to hide it
    2. Replace {{}} with Ng-bind
Separating the interface from the business logic

The controller should not refer directly to the DOM, but should control the behavior of the view. For example, "What happens if a user operates X", "where can I get x?" ”

The Service should not refer directly to the DOM in most cases, it should be a singleton (singletons), independent of the interface, regardless of the view's logic. Its role is simply to "do X operations".

DOM operations should be placed inside the directives.

Reuse existing functions as much as possible

The features you write are probably AngularJS already implemented, and some code can be abstracted out and reused, using a more Angular approach. In short, many of JQuery's cumbersome code can be replaced.

1.ng-repeat

Ng-repeat is very useful. When Ajax obtains data from the server, we often use jQuery (as described above) to add more elements to some of the HTML container nodes, which is bad practice in AngularJS. With the ng-repeat everything becomes very simple. Define an array (model) in your $scope to hold the data pulled from the server, and then use Ng-repeat to bind it to the DOM. The following example initializes the model that defines the friends;

<div ng-init="friends = [{name:‘John‘, age:25}, {name:‘Mary‘, age:28}]">    I have {{friends.length}} friends. They are:    <ul>        <li ng-repeat="friend in friends">            [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.        </li>    </ul></div>

Show results

?
123 I have 2 friends. They are:  [1] John who is 25 years old.  [2] Mary who is 28 years old.

  

2.ng-show

Ng-show is also very useful. It is common to use JQuery to control the display of interface elements based on conditions. But Angular has a better way to do that. Ng-show (and Ng-hide) can decide to hide and display based on Boolean expressions. Define a variable in the $scope:

?
123 <div ng-show="!loggedIn">    点击 <a href="#/login">这里</a> 登录</div>

  

Similar built-in directives and ng-disabled, Ng-switch, etc., are used for conditional control, simple syntax, and are very powerful.

3.ng-class

Ng-class is used to conditionally add class to elements, and we used to do it with jQuery. Angular in the Ng-class of course better use, example:

?
1 <div ng-class="{ errorClass: isError, warningClass: isWarning, okClass: !isError && !isWarning }">...</div>

  

Here Ng-class accepts an object, key is the CSS class name, the value is $scope variable control conditional expression, other similar built-in directives also have Ng-class-even and ng-class-odd, very practical.

$watch and $apply

AngularJS's two-way data binding is the most exciting feature, but it's not all-powerful magic, and in some cases you need to make some minor corrections.

When you use Ng-model, Ng-repeat, and so on to bind the value of an element, AngularJS creates a $watch for that value, as long as the value changes in the range of AngularJS, and all the places are updated synchronously. While you are writing custom directive, you need to define your own $watch to implement this automatic synchronization.

Sometimes you change the value of the model in the code, and the view is not updated, which is often encountered in custom event bindings. You will need to manually invoke scope. $apply () to trigger an interface update. This is illustrated in the example above DatePicker. Third-party plug-ins may have call back, and we can also write the callback function as an anonymous function as a parameter in $apply ().

Combine ng-repeat and other directives.

Ng-repeat is useful, but it is bound to the DOM and it is difficult to use other directives on the same element (such as Ng-show, Ng-controller, and so on).

If you want to use a directive for the entire loop, you can wrap a parent element outside the repeat to write directive there, and if you want to use a directive for each element inside the loop, put it on a sub-node of the ng-repeat.

Scope

Scope should be read-only in the templates template, and it should be write-only in the controller. The purpose of Scope is to refer to model, not to be model. Model is the JavaScript object we define.

$rootScope can be used, but it's likely to be abused.

Scopes form a certain hierarchical relationship in AngularJS, the tree structure must have a root node. Usually we don't have it, because almost every view has a controller and a corresponding scope of its own.

But occasionally there is some data that we want to apply globally to the entire app, when we can inject the data into $rootScope. Because other scopes inherit the root scope, the injected data is available for ng-show such as directive in the local $scope.

Of course, global variables are evil and you have to use $rootScope carefully. In particular, do not use it for code, but just to inject data. If you really want to write a function in $rootScope, it's best to write it into the service so it's only injected when it's used, and it's easier to test.

Conversely, if a function simply stores and returns some data, do not create it as a service.

A partial summary of ANGULARJS

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.