search
HomeWeb Front-endJS TutorialThings to note when developing with Angular.js

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 id="ng-repeat-nbsp-nbsp-content-nbsp">ng-repeat: {{ content }}</h3>
</div>

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

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()
  };
});

Use injection:

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

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();
});

Use injection:

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

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()
    };
  };
});

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

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

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

Configuration

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

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>

JavaScript

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

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

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

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();
  }
}

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


Statement
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
Angular学习之聊聊独立组件(Standalone Component)Angular学习之聊聊独立组件(Standalone Component)Dec 19, 2022 pm 07:24 PM

本篇文章带大家继续angular的学习,简单了解一下Angular中的独立组件(Standalone Component),希望对大家有所帮助!

angular学习之详解状态管理器NgRxangular学习之详解状态管理器NgRxMay 25, 2022 am 11:01 AM

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

项目过大怎么办?如何合理拆分Angular项目?项目过大怎么办?如何合理拆分Angular项目?Jul 26, 2022 pm 07:18 PM

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

聊聊自定义angular-datetime-picker格式的方法聊聊自定义angular-datetime-picker格式的方法Sep 08, 2022 pm 08:29 PM

怎么自定义angular-datetime-picker格式?下面本篇文章聊聊自定义格式的方法,希望对大家有所帮助!

浅析Angular中的独立组件,看看怎么使用浅析Angular中的独立组件,看看怎么使用Jun 23, 2022 pm 03:49 PM

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

手把手带你了解Angular中的依赖注入手把手带你了解Angular中的依赖注入Dec 02, 2022 pm 09:14 PM

本篇文章带大家了解一下依赖注入,介绍一下依赖注入解决的问题和它原生的写法是什么,并聊聊Angular的依赖注入框架,希望对大家有所帮助!

Angular的:host、:host-context、::ng-deep选择器Angular的:host、:host-context、::ng-deep选择器May 31, 2022 am 11:08 AM

本篇文章带大家深入了解一下angular中的几个特殊选择器:host、:host-context、::ng-deep,希望对大家有所帮助!

深入了解angular中的@Component装饰器深入了解angular中的@Component装饰器May 27, 2022 pm 08:13 PM

Component是Directive的子类,它是一个装饰器,用于把某个类标记为Angular组件。下面本篇文章就来带大家深入了解angular中的@Component装饰器,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools