javascript 来自 AJAX 回调的 AngularJS 更新值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12514882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS update value from AJAX callback
提问by arnaslu
When I'm updating scope value directly, it updates in view just fine, but when this value is updated from AJAX callback it doesn't update. Here is simplified example - http://jsfiddle.net/hS8Bs/1/
当我直接更新范围值时,它在视图中更新得很好,但是当这个值从 AJAX 回调更新时它不会更新。这是简化的示例 - http://jsfiddle.net/hS8Bs/1/
How can I get around it?
我怎样才能绕过它?
Update:I noticed that clicking second time on the link does update the value, but it's not what I'm looking for.
更新:我注意到第二次点击链接会更新值,但这不是我想要的。
回答by Renan Tomal Fernandes
The real problem is the lack of $scope.$apply
. When you are updating the angular model outside of the angular digest you should use apply.
真正的问题是缺乏$scope.$apply
. 当您在角度摘要之外更新角度模型时,您应该使用 apply。
$.getJSON('/echo/json/', {}, function(data){
$scope.$apply(function(){
? ? $scope.period = '2010 - 2011';
});
});?
This will trigger the diggest to see the update and if your code inside of apply throw an exception it will be redirected to the $exceptionHandler
service.
这将触发diggest以查看更新,如果apply中的代码抛出异常,它将被重定向到$exceptionHandler
服务。
回答by ako977
This is an addon to the selected answer, I found that Angular JS still called "Error: $digest already in progress" when I implemented the $apply() function.
这是所选答案的插件,我发现当我实现 $apply() 函数时,Angular JS 仍然调用“错误:$digest 已经在进行中”。
So I found Will Vincent'scode on this post: AngularJS : What's the Angular way to interact with a form?, it checks for $digest already in progress and only calls $apply() when safe to:
所以我在这篇文章中找到了Will Vincent 的代码: AngularJS:与表单交互的 Angular 方式是什么?,它会检查 $digest 已经在进行中,并且只有在安全的情况下才调用 $apply() :
$scope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
so it would be something like:
所以它会是这样的:
$scope.safeApply(function() { ...code here... });
$scope.safeApply(function() { ...code here... });
回答by vittore
Here is your missing tutorialyou need to use $http parameter of controller in order to get field updated. Check your updated example http://jsfiddle.net/hS8Bs/2/
这是您缺少的教程,您需要使用控制器的 $http 参数来更新字段。检查您更新的示例http://jsfiddle.net/hS8Bs/2/