我刚刚加入一个新项目,我在角度js代码中看到了很多这样的模式:
_.defer(function () {
$scope.$apply();
});
这对我来说似乎不对,但我不确定为什么。你有什么可能的原因让你等待角度插值完成然后再调用$ scope。$ apply()?
答案 0 :(得分:1)
$apply()
calls $digest()
Under the hood, $digest is angular's internal loop to check if any binded data has changed. Most of the time, you don't need to call $apply yourself because AngularJS takes care of this.
The only cases you need to call $apply is when you use an external lib (for instance when you wrap a jquery lib inside a directive or when using a asynchronous lib such as facebook/twitter) and angular could not possibly know about the DOM changes.
In these cases, you could wrap your code inside $timeout
. It is just a safe way for angular to call $apply when its ready rather than risking the error '$digest already in progress error'
is you directly call $apply.
$timeout (function () {
$scope.update = "something has changed";
});
This way is more the native angular way rather than using the underscore library.
For detailed explanations you can check out this article (a bit old but the core principles of angular stay the same).