Angular novice easy to hit the pit

Source: Internet
Author: User

This article was forwarded from: http://www.ngnice.com/posts/2c8208220edb94

In the angular group to answer the novice question for some time, there are some angular aspects of the pit stay here for reference, hope to be helpful to you. This article will be updated at any time, will not open a new chapter, welcome you to subscribe.

Q1. <div ng-include="views/user/show.html"></div>Where's the mistake?

If you write this, you will find that this position has nothing to load out, then, where is wrong? What is wrong in ng-include needs a variable, if you have such a variable in the $scope $scope.userShowTemplateUrl = "views/users/show.html" , and the above sentence to become <div ng-include="userShowTemplateUrl"></div> normal work. Or you can write this:<div ng-include=" ‘views/user/show.html‘ "></div>

Why?

Because in Ng-include, it interprets its arguments as variables, it calculates the values passed in by $eval and then loads them as template addresses.

However, a better approach is to write these interface fragments (partical) as instructions, so you don't have to repeat the path in multiple places, and more importantly, you can extend its interaction logic directly here in the future, from the smooth evolution of the interface prototype to the online system.

62ω How is my instruction ineffective?

A2. If you exclude a problem such as a code error, the most likely cause is restrict. The Restrict parameter is used to dictate which way you can use the instruction, and this problem is easy to become a pit, because the default value of restrict is a, that is, by default, directives can only be used in the form of attributes, such as I wrote an instruction called Appheader, So by default I can only use it in this form: <div app-header></div> , and <app-header></app-header> the form is invalid.

So, if you use the instruction in the form of a return function, you can only invoke it using the property, for example:

yourModule.directive(‘appHeader‘, function() {  return function(scope, element, attrs) { element.text(‘hello‘); }});

If you want to use an element in a way that uses instructions, you write this:

yourModule.directive(‘appHeader‘, function() {  return { restrict: ‘E‘, // 或‘EA‘等都可以,几种形式可以任意组合 link: function(scope, element, attrs) { element.text(‘hello‘); } }});
Q3. Modified the variable how does the interface not respond?

A3. First of all, of course you have to check if there are any errors and whether it is a scope variable, and if none of this is a problem, then most of it is $apply. For most operations, the $apply automatically executes, so you don't have to worry, but if you use features other than angular, such as calling the SetTimeout function directly, hooking up with jquery events, using jquery Ajax, and so on, Then the system will not be able to help you call $apply, the interface will not have the opportunity to refresh, but if you do other things that will cause $apply, you will find that the previous "owe" interface refresh was normal execution ... The late refresh is still a bug.

The typical code is as follows:

setTimeout(function() {  $scope.time = new Date()}, 1000);

In this case, the time variable you are binding on the page will not be automatically refreshed, either through the {{}} expression or through the Ng-* property or any other form. How to change it? Such

setTimeout(function() {  $scope.$apply(function() { $scope.time = new Date(); });}, 1000);

However, this is not the best form, what is the best form? Of course, using the angular built-in $timeout service, it's doing this:

$timeout(function() {  $scope.time = new Date();});

No $apply, but normal work, no bugs, and more beautiful? But let's not forget that you have to inject the $timeout service, otherwise it is undefined.

Q4. Ng-click written as Ng-class caused the interface to stop responding

A4. This is a low-level mistake I've made, and it's a matter of depth-dependent IDE. The IDE's automatic code hinting function, the first candidate for NG-CL is Ng-class, if the lazy little hit a word, then would like to write Ng-click code will be written ng-class, the result is, endlessly recalculate the expression in Ng-class, One of the reasons has not yet seen the source research.

If you encounter an issue where the interface stops responding, and you are also deeply dependent on the IDE, look at it from this perspective.

Q5. I know you're not a gold digger, but don't forget $

A5. There is a general convention in angular: angular's internal services, methods, and properties usually start with $, and accordingly, it also requires that you do not start with a name of $. It's easier to forget that starting with $ is mainly some method, especially $apply, $watch, $on, $broardcast, $emit These, and these if you write wrong, in Chrome you will get an inexplicable hint typeerror:undefined is not a function! Damn it, even the function doesn't have a name! So, although I know you do not gold, but don't forget to write $!

Q6. Notice the prototype inheritance problem of the scope!

A6. In angular, scopes are inherited through the prototype chain. One problem with this inheritance is that when assigning variables to a subclass, the parent is not modified.

Assuming that Scopea inherits from Scopeb, and a variable value:1 is defined in Scopeb, then the read Scopea.value can fetch the value correctly, but if the assignment is a problem, then what scopeA.value = 2 is the value of Scopeb.value? You might think it's 2, but it's 1! The reason is that the assignment of a variable at prototype inheritance does not modify the value in the prototype, but instead creates a property with the same name directly in the current scope.

This phenomenon leads to a problem that can easily confuse the novice:

The following code works fine:

<Label><InputType="Radio"Ng-model="Color"Value="Red" > Red</Label><Br/><Label><Inputtype= "Radio" ng-model= "color" value= "green" > Green</label><br /><label>< input type= "Radio" ng-model=" color "value=  "blue" > Blue </label><br/>{{color}}        

The following code does not work properly, and the color value will not change with the selection:

<div ng-repeat="value in [‘red‘, ‘green‘, ‘blue‘]">  <label><input type="radio" ng-model="color" ng-value="value"> {{value}} </label></div>{{color}}

The reason for this is that the color value is defined in the current scope, and ng-repeat creates a child scope that inherits from the parent in a way that inherits from the stereotype. Changes to the color value will modify the child's variables, and the parent's variable with the same name will not be modified.

To make it work, change to this:

<div ng-repeat="value in [‘red‘, ‘green‘, ‘blue‘]">  <label><input type="radio" ng-model="vm.color" ng-value="value"> {{value}} </label></div>{{vm.color}}

Here, the color is defined as a property of the VM object, because only the members of the VM need to be assigned, and there is no assignment to the VM, so the assignment will function correctly on the parent scope. The VM here is just an object on the $scope, it can be called another name, just because it's actually viewmodel, so I'm used to naming it as a VM.

After angular 1.2, the Controlleras syntax was introduced to solve this problem once and for all. For specific usage, see http://www.cnblogs.com/whitewolf/p/3493362.html

If you are using a version below 1.2, you can use this syntax in the first sentence of the controller to simulate:

var vm = $scope.vm = {};
All $scope variables are assigned to the VM variable, and the VM variable is referenced in the view.

Q7. Angular.module two ways of writing: a big difference in meaning

angular.module(‘name‘, [])and angular.module(‘name‘) Although it looks very similar, but! Their meanings are very different!

angular.module(‘name‘, [])is to create a new module that [] indicates that it is not dependent on any other modules, and if a module with the same name already exists, it will overwrite the existing one.

Instead, it angular.module(‘name‘) looks for an existing module, and if the module does not exist, it returns a null value.

If the form (create) with square brackets is misused as a form (reference) without square brackets, a null pointer error occurs when functions such as the controller are called on its return value.

If you misuse the reference form as a form of creation, it can lead to an incomprehensible "object does not exist" error, but you clearly defined the service or controller and other objects! This problem is because the module definition that follows covers the previous module definitions, and the objects you have defined are discarded with the previous modules!

Q8. Third-party directives do not work

The most likely cause is that you are not involved in module dependencies. Third-party directives are usually defined in their own modules, so this module must be relied upon by your app module, which contains instructions to be used in view. For example, if you want to use the UI-SELECT2 directive, you must include this dependency in your own module definition:

angular.module(‘app‘, [  ‘ngCookies‘,  ‘ngResource‘,  ‘ngSanitize‘, ‘ui.select2‘]).....

Angular novice easy to hit the pit

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.