Angular.js 在 $scope.var 更改后不会刷新中继器,而只会在刷新后刷新

Angular.js doesn't refresh the repeater after $scope.var changes but only after refresh

本文关键字:刷新 中继器 js scope var Angular      更新时间:2023-09-26

我认为绑定的 2 种方式是有棱角的:

我可以从表单发布到控制器,如果我刷新页面,我会在页面上看到我的输入:

$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);
    });
};

在 html 页面中,ng-repeater遍历for i in input数组。 但是除非我刷新页面,否则不会显示表单中的新输入。

我会很高兴得到帮助 - 谢谢!

尝试$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);
            });
    };

原因是:你的ajax是异步的,它将在下一轮执行,但此时,你已经离开了角循环。角度并不知道这些变化,我们这里要用$scope.$apply进入角度周期。这种情况与使用像$http这样的角度服务略有不同,当您使用$http服务并在.success内处理响应时,angular 会意识到这些变化。

演示

不起作用。您会注意到第一次单击不会刷新视图。

setTimeout(function(){
             $scope.checkboxes = $scope.checkboxes.concat([{"text": "text10", checked:true}]);
         },1);

使用$scope.$apply工作的演示

setTimeout(function(){
            $scope.$apply(function(){
         $scope.checkboxes = $scope.checkboxes.concat([{"text": "text10", checked:true}]);
            });
        },1);