AngularJS1.3 framework usage tips

Source: Internet
Author: User
Tags touch

Some people say that angular1.3 is an obsolete thing, it is recommended to use ANGULAR2. In fact, this kind of saying is like taking jquery1.x and jquery2.x to do comparison, the new version of course will have the advantage of optimization, but not necessarily the most suitable for your project. When your project must support IE6/7/8, you have to use the jquery1.x version. So don't choose a frame or a version of new or new, but see if it fits. Originally used angular1.3 is he more mature have supporting documents, and ANGULAR2 document is not sound, another point is 1.x and 2.x difference is too big, the use of both no inheritance. More importantly, the current ANGULAR2 only has an Alpha version (test) and does not have an official version.

Performance. Some people say that the performance of ANGULAR2 will be better, I have not used, do not make any comments. But for angular1.x, I really do not trust its performance, as PC Web I dare to use angular, but in mobile terminals I dare not use, in my opinion no matter from the frame volume or frame operating efficiency, in the fragile moving end is fatal. There are some hybrid frameworks based on angular (example ionic), and those who wish to use them can tell me how they experience (performance).

Some tips

This article records some angular1.3 tips, angular2 I'll find a time to practice.


1. ng-repeat Multiple field sorting

Using the order by filter, the first argument is an array that is sorted by the values of the properties in the array (if the values are compared by the first item and then by the second), whether the second argument is positive or reverse (the default is positive).

Ng-repeat= "Groupuser in Groupusers | orderby:[' Isowner ', ' isadmin ']:true '


2. Ng-include introduces HTML fragment

Using Ng-include, the first argument is a string of the relative address of the page. It should be noted that it is a string, not a ng-expression, so don't forget to add single quotes, or you'll find out how all of this HTML fragment is not.

<div ng-include= "' msgs.html '" ></div>


3. Ng-bind $scope objects do not change as the data changes

The Ajax that you realize, get the data, set to $scope, view is not updated. This is actually the reason for angular two-way data, angular unforeseen scope changes that will not help refresh view (example $.ajax or settimeout). The solution is that when the data is set to $scope, the $scope is manually tuned. $apply ();

PS: Some instructions (example Ng-click, Ng-model) and services (example $timeout, $http) will automatically refresh view.

4. Mobile Touch Event

The Angular-touch module provides touch events and other gestures Ngswipeleft, ngswiperight.

5. The contents of the ng-bind-html cannot be displayed correctly on the page

Using the Ng-bind-html property, this property relies on $sanitize, which means that the Angular-sanitize.js file needs to be introduced. However, it will be found that the contents of ng-bind-html are not displayed properly on the page because some tags are automatically filtered out by the angularjs as unsafe, and unsafe mode is required to keep these expressions.

<div ng-bind-html= "Article.content | Trusthtml ">
</div>



Myapp.filter (' trusthtml ', function ($SCE) {
return function (Input) {

Return $SCE. trustashtml (input);
}
});

Where $sce is angular's own security processing service, $SCE. trustashtml (Input) returns a trusted object.

6. How to divide a module

My idea is that the pages in a relatively close relationship (business logic) can be zoned as a module, because the page may have a shared service or template or directive (Controller not shared), and these components belong to the same module, We can call it on different pages. A page that you don't want to turn off can be divided into another module to increase the clarity of your code.

7. Do you want to make a service for the tool class

Before we get the project done, I will consider whether to encapsulate some of the tool classes into a service (in order to look code uniform), but I find it unnecessary because the service is owned by a module, and our tool class may be used in different modules and not belong to a module. Introduce the tool class as a library of jquery.

8. Use with Requirejs

Angular does not have the ability to load modules asynchronously, so the effect of using the Requirejs is good. There is some objection to the module definition of the place, is to define a module as a Requirejs module or angular service (can rely on injection), I think or functional attribution of the problem, if it is the global use of tool services, defined as a Requirejs module, And if the module is closely related to the business logic to use the service.

PS: You can avoid caching problems by adding Urlargs to the Requirejs config.

Urlargs: "bust=" + (new Date ()). GetTime ()//can be used to clean up the cache and remove it from deployment to the production environment.


9. IFrame Open cross-domain URL times wrong

<iframe width= "100%" height= "100%" ng-src= "{{URL}}" ></iframe>

If you do not do processing, the above Cross-domain URL is not open, you need to define a whitelist.


Myapp.config (function ($sceDelegateProvider) {
$sceDelegateProvider. Resourceurlwhitelist ([
Allow same origin resource loads.
' Self ',
Allow loading from our assets domain. Notice the difference between * and * *.
"https://link.bingosoft.net/**"]);
});



10. Attribute methods using the scope of other controller


First of all, I don't know if my usage is appropriate. The scope of the use of other controller is limited to its parent scope, and not any controller can be accessed. Scope has a property $parent that allows you to find a scope for a layer of controller.

var parentscope = $scope. $parent. $parent. $parent;

PS: How many layers of $parent i print a scope object to find out.



Some optimization tips for Angularjs


About optimizing ng means there's a lot on the web, the core is all from the $ $watchers the scope of the intrinsic properties, today I say something else, the essence of the same, because this is Ng's mishap, but I believe that as long as the use of appropriate methods, these problems can be avoided.

Introduction to Ng

Angularjs Ng is Google's MVVM framework, which improves the efficiency of front-end project development (in practice it does improve development efficiency), with controllers, instructions, services around the entire project, Internal with unique di to solve the three-layer call before the problem. More details can refer to the NG source analysis I wrote earlier.

Ng's mishap.

When it comes to the mishap, it's a simple principle of data binding.

The model defined on each page in Ng will actually add a listener under the current scope, the internal container is $ $wachers array, as long as any one of the page model changes, will trigger the scope of the internal $digest method, It finds all the model in the current scope tree in turn, is to ensure that the model on the page can get data synchronization, so this is very time-consuming program, the official saying is that when 2000 listeners on the page, the page performance will be significantly reduced. So to improve the performance of NG, we must start from this aspect.

tip1: Bind once

In fact, the internet has been said, here next new usage, Ng's version of 1.3.0+ has provided a syntax to support the model only binding once, see the following example:

Old Code

Hello

New Code


Hello

You can see that the new syntax is in front of the model Plus:: Believe this syntax is more convenient than the Third-party plug-ins used online.

tip2: $scope. $digest vs $scope. $apply

I believe many people are not unfamiliar with the $apply method, it is commonly used when the code is not executed in the NG environment, in order to ensure the data synchronization of the page, the call to the $apply method after the completion of the code execution will trigger the internal $digest to check all the models in the scope, in fact, it is called in the internal , only some snippets of code are written below.


...
...
$rootScope. $digest
...
...

All of which is actually called $digest under the $rootscope root scope, so what's the difference between $digest in different scopes? The most important difference is

$digest only depth to find all models below the caller

So $scope has to save a lot of time to find the model compared to $rootscope.

However, to ensure that all model data on the page is synchronized, or call $rootscope, so before writing the code, it is best to think about what data is synchronized change.

TIP3: Call Ng-repeat as little as possible

Ng-repeat will create a lot of listeners by default, so when the volume of data is very large, this very consuming page performance, I feel that only when you need to update the list of data often need to use ng-repeat, or put so many listeners there is also a waste, at this time can be used with Ng's own $ The Interpolate service parses a piece of code, similar to a static template engine, whose interior relies primarily on the NG Core parsing service $parse, and then assigns the code snippet that fills the data directly to a one-time model.

TIP4: Try to write native grammar in instructions

Although NG provides a lot of instructions such as ng-show,ng-hide, they are to show or hide a piece of code based on the true,false of the model, although it can quickly implement the business requirements, but these instructions still add listeners by default, If the code fragment exists in a large instruction, a better way is to write it in command link. Show (),. Hide () These similar JQ methods to control the better, so that you can save the number of listeners, similar to the own event instructions, In fact, these can be in the peripheral instructions by using AddEventListener to bind the event, anyway, before writing code, it is best to think about how to minimize the number of listeners, so as to improve the overall performance of the page.

TIP5: Use filters as little as possible inside the page

When you add filter behind the model in the page, this will cause the current model to run two times in $digest, causing unnecessary performance waste. The first time when the $ $watchers detection task changes, and the second occurs when the model value is modified, so as to minimize the inline filter syntax, Very impacting page performance like the following

It is recommended to use the $filter service to invoke a filter function in the background, which can significantly improve the performance of the page, the following code

$filter (' filter ') (array, expression, comparator);

Summary

These are some tips to improve the performance of NG projects, although NG is very powerful, but the nonstandard code can also damage its performance, so before writing code, it is best to conceive where the listener is not needed.


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.