Angular.js不刷新转发后$ scope.var变化,但只有刷新后js、Angular、var、scope

2023-09-13 04:51:43 作者:等待你的花语

我想两种方式的结合是角的事情:

I thought 2 ways binding was angular thing:

我可以从形式到控制器后,如果我刷新页面我在页面上看到我输入:

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

在HTML页面在输入数组我在 NG-转发迭代。但是从形式的新的输入没有显示,除非我刷新页面。

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.

我会很高兴与此帮助 - !谢谢

I'll be glad for help with this - thanks!

推荐答案

尝试 $ $范围适用

$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是异步,它会在下一回合执行,但在这个时候,你已经离开角周期。角是不知道的变化,我们必须使用 $范围。$适用这里进入角周期。这个案例是使用来自角服务,如 $ HTTP ,当你使用 $ HTTP 服务和处理有点不同在 .success 您的回复,棱角分明是知道的变化。

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.

演示不起作用。你会发现,第一次点击不刷新视图。

DEMO that does not work. You would notice that the first click does not refresh the view.

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

演示通过使用 $范围的作品。$适用

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