问题描述
AngularJS可以让你实现双向数据绑定。然而,有趣的部分是如何检测模型的变化?该模型通常是这样低于code一个普通的对象。我们可以改变 $ scope.user
的name属性但如何AngularJS检测模式改变了吗?是否AngularJS枚举的 $范围
对象的所有属性?
AngularJS allows you to implement two-way data binding. However, the interesting part is how it detects model changes? The model is usually a plain object like the code below. We can change the name property of $scope.user
but how does AngularJS detect the model changed? Does AngularJS enum all the properties of the $scope
object?
angular.module('myApp', [])
.controller('BusinessCardController', function($scope){
$scope.user = {
name: 'Tanay Pant'
}
});
<input type="text" ng-model="user.name" placeholder="Full Name" />
推荐答案
有一个摘要周期,其中该范围检查所有的$手表前pressions的,并将它们与previous值进行比较。它着眼于对象模型更改,如果旧的价值是不一样的新值,AngularJS会更新适当的地方,a.k.a脏检查。
There is a digest cycle, where the scope examines all of the $watch expressions and compares them with the previous value. It looks at the object models for changes, if the old value isn't the same as the new value, AngularJS will update the appropriate places, a.k.a dirty checking.
为了使消化周期将执行 $申请(FN)
已被运行,这是你如何从JavaScript进入角的世界。如何 $应用。(FN)
被调用(从AngularJs的集成):
In order for the digest cycle to be execute $apply(fn)
has to be run, this is how you enter the Angular world from JavaScript. How does $apply(fn)
get called (taken from AngularJs integration with browser):
- 浏览器的事件循环等待事件的到来。一个事件是用户的交互,定时器事件或网络事件(从服务器响应)。
- 本次活动的回调被执行。该进入的JavaScript环境。回调可以修改DOM结构。
- 一旦回调执行,浏览器离开JavaScript的背景和重新呈现基于DOM的看法改变了。
为了实现双向绑定,指令寄存器观察家。对于一个页面要快速,高效,我们需要尽量减少我们创造的所有这些观察家。即只使用它,你真正需要的时候 - 所以,你应该用双向绑定时要小心。否则,使用单向的:
In order to achieve two-way binding, directives register watchers. For a page to be fast and efficient we need to try and reduce all these watchers that we create. So you should be careful when using two-way binding - i.e. only use it when you really needed. Otherwise use one-way:
&LT; H1&GT; {{:: vm.title}}&LT; / H1&GT;
下面这是很明显的是,网页的标题可能不会在用户在页面上改变 - 或需要,看它是否被改变的新的。因此,我们可以使用:
注册一个单向的过程中模板链接阶段绑定。
Here it is quite obvious that the title of the page probably won't be changed while the user is on the page - or needs to see the new one if it is changed. So we can use ::
to register a one-way binding during the template linking phase.
我见过有观察家爆炸的主要问题与数百行的网格。如果这些行有好几个列和每个细胞有双向数据绑定,那么你就请客。你可以坐下来和近代等待像网页加载!
The main issues I've seen with explosions of watchers are grids with hundreds of rows. If these rows have quite a few columns and in each cell there is two-way data binding, then you're in for a treat. You can sit back and wait like in modem times for the page to load!
这篇关于如何AngularJS实现其双向数据绑定机制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!