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('{[{'); $interpolateProvider.endSymbol('}]}'); });
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: 'ng-annotate!babel?presets=es2015' },
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

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
