angularjs – $scope.apply();之间的差异和$scope.apply(function(){});

前端之家收集整理的这篇文章主要介绍了angularjs – $scope.apply();之间的差异和$scope.apply(function(){});前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
拿这个代码

$scope.$apply(function(){
    $scope.foo = 'test';
});

与这一个:

$scope.foo = 'test';
$scope.$apply();

这两者有什么区别?我试过搜索但找不到任何关于此的信息.

甚至这种方法

$scope.$apply('foo = "test"');

解决方法

您在评论中引用的文章是正确的.唯一的区别是,如果你传入一个函数,那么该函数将在$digest循环的其余部分之前被“应用”(或$digested).因此,如果您希望Angular立即识别您的特定更改(意味着在评估所有其他更改之前),您应该传入一个函数.否则,$scope.$apply()和$rootScope.$digest()之间没有区别.

文章说:

What is $apply?
Simply put,it’s a wrapper around $rootScope.$digest that evaluates any expression passed to it prior to calling $digest(). That’s it. So,if you’re calling it by itself without passing an argument to it,you may as well just call $digest().

希望有所帮助.

猜你在找的Angularjs相关文章