Home > Web Front-end > JS Tutorial > Things to note when developing with Angular.js

Things to note when developing with Angular.js

高洛峰
Release: 2016-12-09 16:07:16
Original
1030 people have browsed it

Foreword

I have been playing with Angularjs recently. I have to say that compared to Knockout, the MVVM framework of Angularjs is more powerful and more complex. Various tutorials are everywhere on the Internet, but when you actually use it in a project, you will encounter various pit.

1. ng-repeat

ng-repeat is used to identify that an elem needs to be output repeatedly, and the content of the repeated output must be unique

<div ng-app="app" ng-controller="control">
  <h3 ng-repeat="content in repeatContent">ng-repeat: {{ content }}</h3>
</div>
Copy after login

let app = angular.module("app", []);
app.controller("control", ($scope) => {
  // 输出李滨泓
  $scope.repeatContent = ["李", "滨", "泓"];
  // 下面存在两个“泓”,会报错
  // $scope.repeatContent = ["李", "滨", "泓", "泓"];
})
Copy after login

2. Between provider, service, factory The relationship

factory

factory is very similar to service. The difference is that service is a singleton object in Angular. That is, when you need to use service, use the new keyword to create one (and only one) service. Factory is an ordinary function. When needed, it is just a method of calling an ordinary function. It can return various forms of data, for example, by returning a collection object of functional functions for use.

Definition:

let app = angular.module("app", []);
 
// 这里可以注入 $http 等 Provider
app.factory("Today", () => {
  let date = new Date();
  return {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate()
  };
});
Copy after login

Use injection:

app.controller("control", (Today) => {
  console.log(Today.year);
  console.log(Today.month);
  console.log(Today.day);
});
Copy after login
Copy after login

service

service is a singleton object when used, and it is also a constructor. Its characteristics allow it to not return anything. Because it is created using the new keyword, it can also be used for communication and data interaction between controllers, because the scope chain of the controller will be destroyed when it is useless (for example, using a route to jump to another page, and using another controller)

Definition:

let app = angular.module("app", []);
 
// 这里可以注入 $http 等 Provider
// 注意这里不可以使用 arrow function
// arrow function 不能作为 constructor
app.service("Today", function() {
  let date = new Date();
  this.year = date.getFullYear();
  this.month = date.getMonth() + 1;
  this.day = date.getDate();
});
Copy after login

Use injection:

app.controller("control", (Today) => {
  console.log(Today.year);
  console.log(Today.month);
  console.log(Today.day);
});
Copy after login
Copy after login

provider

provider is the underlying creation method of service. It can be understood that provider is a configurable version of service. We can formally inject it Configure some parameters of the provider before the provider.

Definition:

let app = angular.module("app", []);
 
// 这里可以注入 $http 等 Provider
// 注意这里不可以使用 arrow function
// arrow function 不能作为 constructor
app.provider("Today", function() {
  this.date = new Date();
  let self = this;
 
  this.setDate = (year, month, day) => {
    this.date = new Date(year, month - 1, day);
  }
 
  this.$get = () => {
    return {
      year: this.date.getFullYear(),
      month: this.date.getMonth() + 1,
      day: this.date.getDate()
    };
  };
});
Copy after login

Use injection:

// 这里重新配置了今天的日期是 2015年2月15日
// 注意这里注入的是 TodayProvider,使用驼峰命名来注入正确的需要配置的 provider
app.config((TodayProvider) => {
  TodayProvider.setDate(2015, 2, 15);
});
 
app.controller("control", (Today) => {
  console.log(Today.year);
  console.log(Today.month);
  console.log(Today.day);
});
Copy after login

3. Handlebars conflict with angular symbol resolution

Scenario:

When I use node.js as the server, and used handlebars serves as a template engine. When node.js responds and renders a URL, its template uses { {} } as the variable parsing symbol. Similarly, angular also uses { {} } as variable resolution symbols, so when node.js renders the page, if the variables in { {} } do not exist, the area will be cleared, and my original intention is this It is used for angular's parsing instead of handlebars. At the same time, I also want to continue to use handlebars, so at this time I need to redefine angular's default { {} } parsing symbol. That is to say, use dependency injection $interpolateProvider to define it, as shown in the following example:

app.config($interpolateProvider => {
  $interpolateProvider.startSymbol(&#39;{[{&#39;);
  $interpolateProvider.endSymbol(&#39;}]}&#39;);
});
Copy after login

IV. ng-annotate-loader

ng-annotate-loader is applied to the development scenario of webpack + angular, and is used to solve the problem of angular in progress Solution to dependency injection failure and error after JS compression

Installation

$ npm install ng-annotate-loader --save-dev
Copy after login

Configuration

// webpack.config.js
{
  test: /\.js?$/,
  exclude: /(node_modules|bower_components)/,
  loader: &#39;ng-annotate!babel?presets=es2015&#39;
},
Copy after login

5. Two-way data binding

When we use events that are not provided by Angular , the data change in $scope will not cause the dirty-checking cycle of $digest, which will cause the view to not be updated synchronously when the model changes. At this time, we need to actively trigger the update ourselves

HTML

<div>{{ foo }}</div>
<button id="addBtn">go</button>
Copy after login

JavaScript

app.controller("control", ($scope) => {
  $scope.foo = 0;
  document.getElementById("addBtn").addEventListener("click", () => {
    $scope.foo++;
  }, false);
})
Copy after login

Obviously, the intention of the example is that when the button is clicked, foo will grow and update the View, but in fact, $scope.foo changes, but the View does not refresh, because foo does not have a $watch to $apply after detecting changes, which ultimately causes $digest, so we need to trigger $apply ourselves or create a $watch to trigger or detect data changes

JavaScript (using $apply)

app.controller("control", ($scope) => {
  $scope.foo = 0;
  document.getElementById("addBtn").addEventListener("click", () => {
     
    $scope.$apply(function() {
      $scope.foo++;
    });
 
  }, false);
})
Copy after login

JavaScript (using $watch & $digest)

app.controller("control", ($scope) => {
  $scope.foo = 0;
  $scope.flag = 0;
 
  $scope.$watch("flag", (newValue, oldValue) => {
 
    // 当 $digest 循环检测 flag 时,如果新旧值不一致将调用该函数
    $scope.foo = $scope.flag;
  });
 
  document.getElementById("addBtn").addEventListener("click", () => {
     
    $scope.flag++;
    // 主动触发 $digest 循环
    $scope.$digest();
  }, false);
})
Copy after login

6. $watch(watchExpression, listener, [objectEquality])

Register a listener callback function and call

watchExpression every time the value of watchExpression changes Called every time $digest is executed, and returns the value to be detected (when the same value is entered multiple times, watchExpression should not change its own value, otherwise it may cause multiple $digest loops, watchExpression should be exponentiated etc.)

listener will be called when the current watchExpression return value is inconsistent with the last watchExpression return value (use !== to strictly judge the inconsistency instead of using ==, except for objectEquality == true)

objectEquality is a boolean value. When it is true, angular.equals will be used to determine the consistency, and angular.copy will be used to save this Object copy for the next comparison, which means that complex object detection will There will be performance and memory problems

7. $apply([exp])

$apply is a function of $scope, used to trigger the $digest loop

$apply pseudo code

function $apply(expr) {
  try {
    return $eval(expr);
  } catch (e) {
    $exceptionHandler(e);
  } finally {
    $root.$digest();
  }
}
Copy after login

Use $eval(expr) to execute the expr expression

If an exception occurs during execution, then execute $exceptionHandler(e)

In the end, regardless of the result, the $digest loop will be executed once


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template