Angular Application Skills Summary _angularjs

Source: Internet
Author: User
Tags in python

Angular's core idea is to drive everything through data, and everything else is an extension of the data.

The idea of applying JavaScript to everything is that everything is data in angular.

About Project Building

(1) Requirejs and Yeoman

At the beginning of contact or use of angular, always puzzled and similar problems, I practice the answer is no need Requirejs or Yeoman. The former is not used, Because the angular itself has the implementation of module. The latter is because the angular organization and project construction are not so complicated, handwritten or pull a seed project on GitHub.

(2) How to organize the project structure

This problem is a bit of a waste, because it's totally different because of the project. The personal recommendation is two organizational structures, one that follows the code function, that is, the controller are placed under a folder, and services are placed under one folder. The other follows the functionality that is implemented, For example, the user puts the corresponding Template,services,controller under the user folder.

Both can be, from the maintenance point of view the second will be better.

(3) Division of Controller and service

Here controller is usually a page of a controller, if a page has a public part, the public part always uses a controller. For service to be divided into two parts, one is the service of server interactive data, Another is the content of some functional common, which put some of their own reusable services, similar to the Notify and so on.

As for the service should not be further divided according to the function and module, this depends on the project.

(4) The use of angular plug-ins and libraries

For a project all the things to go online to get ready-made is not realistic, but all things are written by themselves is even less practical. Many of angular's plug-ins are developed by the angular team or some people use the jquery plugin. My view of the plug-in is very simple, if you use the demand can be satisfied with the need to be satisfied with their own writing or in the existing plug-ins to improve.

For a few hours of debugging if you do not have the plug-in, listen to my advice, give it up. Most plug-ins are some UI plug-ins, can not be pursued complex, and sometimes simple HTML control has its own simplicity of the United States.

If you encounter angular plug-in conflicts, especially UI plug-ins, most of the cases will give up one of them, such as Angular-ui and Angular-strap.

Use Tips

Below, I'll enumerate some of the techniques I use in using angular, and I'll enumerate them in the form of a scene. Here are some of the basic concepts of angular I don't explain, this is some technical stuff, not a basic tutorial.

(1) Angular "{{}}" flask conflict in Python

In the template used by Python's flask, data binding is also through two "{" Curly braces, which conflict with angular data binding. There are two solutions to this, one is to modify the angular binding tag, the other is to modify the flask binding tag, both of which are given .

Modify Angular:

$interpolateProvider. Startsymbol (' {[{')]. Endsymbol ('}]} ');
Add this sentence to config, and place it in the route module. This will bind the original angular {{}} to the {{}}} binding.

Modify Flask:

Class Customflask (flask):
  jinja_options = Flask.jinja_options.copy ()
  jinja_options.update (Block
    _start_string= ' {% ',
    block_end_string= '%} ',
    variable_start_string= ' {# ',
    variable_end_string= ' #} ',
    comment_start_string= ' <# ',
    comment_end_string= ' #> ',
  )
  
app = Customflask (__name__, Instance_path= '/web ')

Here I recommend to modify the flask, because after using the angular, the front and rear separation. The Jinjia template for flask is no longer needed, and if you modify the angular binding tag, other controls and libraries will be problematic.

(2) Remove always default with "#" in URL

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
 }
];
  

(3) ng-click= "expression" and similar instructions, how to write multiple expressions in expression?

For example, I want to assign a value to 2 variables in a ng-click, by ";" Semicolons can be split:

<a ng-click= "obja=1;objb=2" ></a>

(4) $watch does not have a function or only takes effect once

This situation usually occurs when listening to a string or number, $scope. $watch ("name", function () {}). Not in effect or only once, the solution is $watch as much as possible to monitor an object, Attach the value you want to listen to under one object.

This is obvious when you use the modal in the Angular-ui. The specific reason is because of the $scope inheritance, because modal is equivalent to creating a scope in the controller of the current page, so there is no way to retrieve the trace prototype chain for literal quantities, There is an object to be resolved in order to implement a data refresh binding across the parent-child scope through the prototype chain.

(5) Want to Ng-view content full page display

Usually a page may have a fixed top-menu or sidebar, this kind of fixed-invariant parts, and then each route change is Ng-view template, if a page wants the entire page to fully display its own, not including the Top-menu and other fixed parts .

Here is usually a index.html and a ng-view display of Template.html,top-menu and sidebar are located in Index.html, and their display is hidden through ng-if binding a variable control.

If a page needs to be fully displayed, does not display sidebar, and so on, it is passed through the $scope in its controller. $emit send a message up, and then the index page controller through $scope. $on listen to the message, and once you hear it, , the variable that controls sidebar explicit is changed.

can also make a global variable control through service, personal recommendation or through the message broadcast way.

(6) Remember to replace Ng-show with Ng-if

This is a little pit of angular, it can be said to be a kind of a pit. Some long list data, there may be some things are hidden by default, click on the display of the form to show. And this part of the control of the hidden content will also be accompanied by a lot of data binding. This is very impacting performance when rendering the page.

For example, usually angular suggest a page of data binding of not more than 2000, if there is a page directly bound to 2000 model, and then you load, you will find the very card. If you set each 100 model to ng-show, it is not displayed by default, You'll find it's still a lot of cards.

Then you replace all the ng-show with Ng-if, and you'll find that performance is instantaneous like two apps. The reason is that all of the bindings are executed in ng-show or all of them, and Ng-if will perform the binding when it is equal to true, that is, the display. So the performance is greatly improved, Before I passed this simple modification, the page load was about 10 times times faster.

So when you can use ng-if, use it instead of all the ng-show and ng-hide.

(7) About ng-bind-html

Typically binding data for HTML elements, Ng-bind is enough, but some situations need to bind not the general data, but the HTML. Then Ng-bind is not enough, need to use ng-bind-html, It outputs the content as HTML. For example, if you want to output HTML with class, use ng-bind-html, and you need to ngsanitize the appropriate file.

(8) The results after obtaining the Ng-repeat data filter

This generally needs to be used when searching, such as multiple ng-repeat data form a list. Then filter a field, now to get the result of the filter, there are 2 ways.

One is written in the ng-repeat of HTML like this:

ng-repeat= "Food in foodcategory._displayfoods = (Foodcategory.foods | filter: {' name ': Searchobj.foodfilter} | By: Food.sort_order) "

So _displayfoods is the result of the final display after the filter. Another way is through two sets of data, one written in the controller, and then the filter and the by-by are operated in controller, The result of the last operation is used to ng-repeat.

The first way is more convenient, the second way is better, the performance is good.

(9) Ng-class and Ng-style by judging the value of the assignment

Determines whether a class is applied, and a different style style, depending on the value of the variable.

ng-class= "{' State-error ':!foodform.foodstock. $valid}"

ng-style= "{color:i.color==" | | | i.name== ' live '? ' Default ': ' #fff '} '

(a) Form validation takes input as an example

Angular form can be validated by the HTML5 attribute of input, which is mainly locked by the form and the Name property of input formname.inputname.$ Valid indicates whether the space named InputName is validated by its own property.

(one) the $promise of $resource and $http

$q. All ([
 resource.query (). $promise,
 resource2.query (). $promise
]). Then (Functon (Success) {
 Console.log (success);
},functon (Error) {
 console.log (error);
});
FoodFactory.food.save (f). $promise. Then (function (Result) {
 foodFactory.food.get ({id:result.id}). $ Promise.then (function (data) {
 });

This does not explain, direct look on it, pay attention to the $http promise need to manually return, so generally all through $resource.

(12) Only one attribute in the $watch listener collection

The third parameter of the $watch is set to true to deep watch. But sometimes you don't want to or you don't need to listen to all the properties of collection. Just watch one or several of them, this time through the for loop although it can loop $watch but obviously too bad.

By following this notation, you can monitor a single Collection object property.

$scope. People = [
  {"
    groupname": "G1", 
    "persions": [
      {
        "id": 1, 
        "name": "Bill"
      }, 
      {
        "id": 2, 
        "name": "Bill2"
      }
    ]
  }, 
  {
    "groupname": "G2", 
    "persions": [
      {
        "id": 3, 
        "name": "Bill3"
      }, 
      {
        "id": 4, 
        "name": "Bill4"
      }
    ]
  }
]

$ Scope. $watch (function ($scope) {return
  $scope. People.map (function (obj) {return
    Obj.persions.map ( Function (g) {return
      g.name
    });
  };
}, Function (newval) {
  $scope. count++;
  $scope. msg = ' person name is changed ' + $scope. Count;
}, True);
  

(debounce) Stabilization process

This is useful for frequent departures, and for scenarios like Ng-change, $watch. such as the eradication of keyword Instant Search, the $debounce encapsulated as a service, directly invoke the interface, code: http://jsfiddle.net/Warspawn/6K7Kd/

(14) Fast positioning to a location

Generally speaking, the page through the <a id= "bottom" ></a> such forms can be combined with JS code, to achieve rapid positioning. In angular, it is done by a similar principle, the code is 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.

summed up so much, a lot of things are looking at the data and their own practice, I hope the need for the TX will be helpful, if there is something new will continue to write.

The above is the angular application skills summary, follow-up continue to add finishing related articles, thank you for the support of this site!

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.