Angularjs problems encountered in the project and optimization summary __js

Source: Internet
Author: User
problems encountered by ANGULARJS in project and the summary of optimization

Because the minimum requirement for this project is a compatible IE8 browser, select the Angularjs1.2 version on the version selection. 1.ng-if/ng-switch and ng-show/ng-hide the choice ng-show/ng-hide is to control the display and hiding of elements by modifying the CSS style, and the corresponding DOM elements will always exist in the current page. The essence is that the CSS attribute operates Display:none;display:block, and Ng-if dynamically adds a delete page element to the current page based on the value of the expression. If the value of an assignment expression is false, the element is deleted from the page, or an element is added. Ng-if creates an element with the code it compiles, and if the code inside the Ng-if is modified by other means, the modification will only work for this show, and the modification will disappear after the page element is rendered, and ng-show/ng-hide can preserve the state of the DOM element last modified. In terms of scope, there is also a difference: When an element is removed from the DOM by NG-IF, its associated scope is also destroyed. And when it rejoin the DOM, a new scope is generated, and ng-show and ng-hide do not.

Because more than one list of data is required in the project, if the DOM elements are frequently rebuilt and removed, the performance is very high, so use ng-show for performance considerations.

There is, of course, another case where there are long list data, and there may be some things that are hidden by default, Click on the display to show the form. This part of the control of the hidden content will also be accompanied by a lot of data binding. This affects performance when the page is rendered. (Angular suggest a page with no more than 2000 data binding, if there is a page directly bound 2000 model, and then you load , you will find the very cards. If you set every 100 model to ng-show, you will find that it is still very card by default. Then you replace all ng-show with Ng-if, You will find that performance is instantaneous like two applications. The reason is that all of the bindings are ng-show or executed, and the ng-if will then perform the binding when it is equal to true, that is, the display. The performance is greatly improved.




Ng-show = False


Ng-show=true


Ng-if = True


Ng-if = False



Angular.module ("App", []). Controller ("Mainctrl", function ($scope) {
});

Example Demo 2 bidirectional data binding {{}} using Refresh to present { {}}

Because the background data problem is not successfully accessed, the foreground interface does not need to show {{}}, using the Ng-bind directive instead of {{}} 3 Rootscrope and the difference from rootscrope and scope. rootscrope page All rootscrope pages all of the scope of the father. How to generate Rootscope and rootscope and scope

step1:angular resolves the ng-app and then creates the $rootscope in memory.

Step2:angular to continue parsing, find the {{}}} expression or Ng-bind instruction, and parse it into a variable.

Step3: Then parses the div with Ng-controller and points to a controller function. This time in this controller function becomes a $scope object instance. 4 always default with "#" in URL removal using routing

When setting the route, turn on the HTML5 mode.

Angular.module (' router ', [' Ngroute '])
. config ([' $routeProvider ', ' $locationProvider ',
  function ($ Routeprovider, $locationProvider) {
    $locationProvider. Html5mode (true);   Set this sentence to
  }
];
5 page Quick position element position

Generally speaking, this form can be combined with JS code, to achieve rapid positioning. In angular, it is done by a similar principle, as follows:

var old = $location. hash ();
$location. Hash (' Batchmenu-bottom ');
$anchorScroll ();
$location. hash (old);

This is written because the direct location.hash will cause URL changes, page jump, so added to prevent the jump code. 6 using Routing switches different modules need to be fully displayed when using routing development, switching routes will remove the div from the previous module and add the next template again. There may be requirements in general projects to fix header headers and sidebar, so that each change between different templates is Ng-view of Ui-view (template) within ui-route (native Ngroute). If there is a page that requires the browser to display the entire full page, excluding the head and sidebar. You can use the NG-IF binding variable to control the display and concealment of the head and sidebar.

1. Can be directly in the service to do a global variable control

2. Message broadcast mode: The binding of specific variables can be controller through scope. Scope.emit sends a message up, and then the page controller through scope. Scope.on listens for messages, and changes the value of the variable once the message is received. 7 Use of Ng-repeat

There is a requirement in the project that needs to be in real time with the new list data according to the traditional practice is to use the timer every 10000ms to the background to send the request, and the original data contrast, the data with the new first remove the original list Div, and then dynamically add new data list, generally do not use any framework of the case, It's all in jquery, but there's a problem with the fact that there's a lot of real time data that needs to be done by the DOM, and DOM operations are very performance-intensive.

Taking into account the above problems, using the angular internal service HTTP for background data request, while in the controller using HTTP for background data request, while using scope in the controller. $watch () monitor the changes in data, and whether the old data compare to change, Then use the internal instruction ng-repeat facilitate the array to generate the DOM elements for the list to display.

Ng-repeat in the use of the process also to consider a performance problem, the pit should be very careful, otherwise the overall performance of the promotion is not very small.

For the convenience of illustration, here is a small example.

 <body ng-app= "myApp" ng-controller= "Myctrl" > <button ng-click= "request ()" > re-request new data </button> <ul> <li ng-repeat= "data in Records" >{{data.name}}</li> </ul> </body> <script
> var app = angular.module ("myApp", []);
    App.controller ("Myctrl", function ($scope) {var data1 = [];
    var data2 = [];
        for (var i = 0; i < 3; i++) {data2[i] = Data1[i] = {id:i, name: "Jay:" + I
    };
        for (var i = 0; i < 3; i++) {Data2[i] = {ID: "id" +i, Name: "Sum:" + I       
    };
    $scope. Records = Data1;
        $scope. Request = function () {//Simulate loading new data from server var result = Data2;
    directly reassign the value to records $scope. Records = result;
};
}); </script> 

Start to show the list of data1 arrays, click on the request data, and then replace the data in the $scope.records data2,data1 and data2 length are the same but the content is different. Re-request the data, see the source code in the ng-repeat can be found, when the array content in Ng-repeat changes, the original DOM will be deleted, based on the new data to regenerate the new DOM elements.

    Remove existing items for
  (key in Lastblockmap) {
    //Lastblockmap are we own object so we don ' t need to use SPE cial hasownpropertyfn
    if (Lastblockmap.hasownproperty (key)) {block
      = Lastblockmap[key];
      Elementstoremove = Getblockelements (block.clone);
      $animate. Leave (elementstoremove);
      ForEach (elementstoremove, function (Element) {element[ng_removed] = true;});
      Block.scope. $destroy ();
    }
  }

Break into the code in the operation, found that even if the use of the Ng-repeat directive, or DOM for frequent elimination and reconstruction operations, the performance of the Ascension does not have much effect, we do not think why Ng-repeat can not take advantage of the existing DOM elements to the new loaded data, Instead of frequent remove and create.

After viewing Ng-repeat's usage API, Ng-repeat has a track by $index code.

<li ng-repeat= "data in records track by $index" >{{data.name}}</li>

After adding this code, refresh back to our example, found that the click of the request to load data, did not enter the section of the code. This is why.

Delete Track by $index code, re-operation add the previous demo, you can see Ng-repeat to the array of each newly added element adds a $ $hashkey attribute, this key is generated by the Nextuid () method inside the ANGUALR. A database-like ID number that is uniquely labeled with a string. This makes clear why the DOM cannot be reused, because each substitution array causes Ng-repeat to generate a new key for each element to uniquely identify, so there is no way to reuse the existing DOM element.

When using ng-repeat, try to avoid refreshing the global list. Ng-repeat produces a $ $hashkey attribute and a system-only item. This means that when you call Scope.listboundtongrepeat = Serverfetch (), a refresh of the entire list is caused. Notifies you that all watchers are executed and triggers each element, which is very consuming performance. Here are a couple of solutions. One is to maintain two sets, and ng-repeat with filters (which basically require custom synchronization logic, so the algorithm is more complex and less maintainable), and the other is to use track by to specify your own key (angular 1.2 to start support, Requires little synchronization logic only).

After adding the track by $index, re-view and discover that the $ $hashkey property does not appear in the newly added array so that ng-repeat can cache it and simply replace the data in the DOM to improve performance.

We also looked at the new state of the DOM tree to see if we recreated the DOM or just replaced the data.

8. Use two-way data binding to build multi-level linkage operation

Two-way data binding to build multilevel linkage operation
9 Discussion on the GitHub of Ui-router memory leak problem

Routing Memory leak problem

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.