angular.js $scope.$apply 不适用于 ng-repeat

angular.js $scope.$apply wont work on ng-repeat

我过去一直使用 $scope.$apply 来处理 $http 请求,我在这个请求上遗漏了什么? 我首先收到了 "Digest cycle is already in progress" 消息,然后添加了 setTimeout() ,它摆脱了该消息,但 ng-repeat 仍然不会更新数据。这应该不是问题,我显然遗漏了一些东西。

HTML:

<form name="userDataForm" role="form" ng-submit="submit()">
<input type="text" name="userId" placeholder="Enter User ID" ng-model="viewModel.useId" />
<input type="text" name="start" placeholder="Start Date: dd-mm-yyyy" ng-model="viewModel.startDate"/>
<input type="text" name="end" placeholder="End Date: dd-mm-yyyy" ng-model="viewModel.endDate"/><br/>

<button type="submit">
    Get Data
</button>
<ul ng-repeat="place in viewModel.userData.data.significant_places">
    <li>
        You have been at <span style="color:red;">{{place.name}}</span> <span style="color:red;">{{place.number_of_days}}</span> days this month
    </li>
<ul>

JS

$scope.viewModel = {
    userId:'',
    startDate:'',
    endDate:'',
    userData:{}
};
$scope.submit = function(){
                 setTimeout(function(){
                    $scope.$apply(function(){
                        $http.get('http://localhost:3000/?user_id=279&start=20150101&end=20150113').success(function(data){
                            $scope.viewModel.userData = data;
                        }).error(function(){
                            console.log('error');
                        });
                    });
                 }, 1)


};

这应该可以正常工作:

$scope.viewModel = {
    userId:'',
    startDate:'',
    endDate:'',
    userData:{}
};
$scope.submit = function(){

    $http.get('http://localhost:3000/?user_id=279&start=20150101&end=20150113').success(function(data){
        $scope.viewModel.userData = data;
    }).error(function(){
        console.log('error');
    });

};

很少有需要自己使用的情况 $scope.$apply。 Angular 几乎总是为你做这件事(这就是你得到那个错误的原因)。