javascript Angular.js 在 $scope.var 更改后不会刷新转发器,但只会在刷新后刷新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19516098/
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
Angular.js doesn't refresh the repeater after $scope.var changes but only after refresh
提问by alonisser
I thought 2 ways binding was angular thing:
我认为 2 种绑定方式是有角度的事情:
I can post from a form to the controller, and if I refresh the page I see my input on the page:
我可以从表单发布到控制器,如果我刷新页面,我会在页面上看到我的输入:
$scope.loadInput = function () {
$scope.me.getList('api') //Restangular - this part works
.then(function(userinput) {
$scope.Input = $scope.Input.concat(userinput);
// scope.input is being referenced by ng-repeater in the page
// so after here a refresh should be triggered.
},function(response){
/*@alon TODO: better error handling than console.log..*/
console.log('Error with response:', response.status);
});
};
In the html page the ng-repeater
iterates over the array of for i in input
. but the new input from the form isn't shown unless I refresh the page.
在 html 页面中,ng-repeater
迭代for i in input
. 但是除非我刷新页面,否则不会显示表单中的新输入。
I'll be glad for help with this - thanks!
我很乐意为您提供帮助 - 谢谢!
采纳答案by Khanh TO
Try $scope.$apply
:
尝试$scope.$apply
:
$scope.loadInput = function () {
$scope.me.getList('api') //Restangular - this part works
.then(function(userinput) {
$scope.$apply(function(){ //let angular know the changes
$scope.Input = $scope.Input.concat(userinput);
});
},function(response){
/*@alon TODO: better error handling than console.log..*/
console.log('Error with response:', response.status);
});
};
The reason why: Your ajax is async, it will execute in the next turn, but at this time, you already leaves angular cycle. Angular is not aware of the changes, we have to use $scope.$apply
here to enter angular cycle. This case is a little bit different from using services from angular like $http
, when you use $http
service and handle your response inside .success
, angular is aware of the changes.
原因:你的ajax是async的,下一回合会执行,但是这个时候你已经离开了angular cycle。Angular 是不知道变化的,我们要使用$scope.$apply
这里来进入 angular 循环。这种情况与从 angular like 使用服务有点不同$http
,当您使用$http
service 并在里面处理您的响应时.success
,angular 会意识到这些变化。
DEMOthat does not work. You would notice that the first click does not refresh the view.
DEMO不起作用。您会注意到第一次单击不会刷新视图。
setTimeout(function(){
$scope.checkboxes = $scope.checkboxes.concat([{"text": "text10", checked:true}]);
},1);
DEMOthat works by using $scope.$apply
通过使用工作的演示$scope.$apply
setTimeout(function(){
$scope.$apply(function(){
$scope.checkboxes = $scope.checkboxes.concat([{"text": "text10", checked:true}]);
});
},1);