Angular,在更改模型时视图不更新

时间:2014-03-20 07:31:13

标签: javascript angularjs

我正在更改模型,我期待视图更新,但它不是:

以下是我的观点:

<div ng-controller="showCarCtrl">
                <h1>Damaged Cars</h1>
                <table border="1">
                        <tr>
                                <th>Plate Number</th>
                                <th>Brand</th>
                                <th>Color</th>
                        </tr>
                        <tr ng-repeat="car in cars" ng-show="car.damaged">
                                <td>{{car.plate_number}}</td>
                                <td>{{car.brand}}</td>
                                <td>{{car.color}}</td>
                                <td>
                                        <button ng-click="setRepaired(car.cid)">Repaired</button>
                                </td>
                        </tr>
                </table>
        </div>

这是控制器:

app.controller('showCarCtrl', function($scope, $rootScope,CarService){
$scope.setDamaged = function(cid){
                console.log("setting the car as damaged "+cid)
                $rootScope.loading = true;
                CarService.setDamageCar(cid)
                            .then(function(data){
                                $rootScope.loading = false;
                                console.log("set damage 1")
                                for(var i=0; i<$scope.cars.length; i++) {
                                        console.log("setting car as damage");
                                        if ($scope.cars[i]==cid) {
                                                $scope.cars[i].damaged = 1
                                                $scope.$apply();
                                                console.log("it enters here");
                                                break;
                                        }
                                        console.log($scope.cars)
                                }
                            },

                            //deferred
                            function(data){
                                console.log('Car Service failed');
                                $rootScope.loading = false;
                            });
        };

});

我已经从服务器检查过,来自服务器的回复是正确的,我在$scope.cars[i].damaged = 1成功更新了模型,唯一的问题是我希望视图能够改变因为如上所示,在视图中,我的内容为<tr ng-repeat="car in cars" ng-show="car.damaged">,但视图未更新

1 个答案:

答案 0 :(得分:2)

我认为您的代码中存在错误:

if ($scope.cars[i]==cid) {

也许它应该是这样的:

if ($scope.cars[i].cid === cid) {