0

我在控制器中有一个函数,它告诉我资源是否已更改,因此只有在没有更改的情况下才会发送服务器请求以保存对象。最初调用 is clean 函数时,它工作正常。但是,当它在由ng-click事件触发的另一个函数内部调用时,我会得到不同的结果。为什么会这样?

示例代码

app.controller('EditorController', ['$scope', 'Item' function($scope, Item) {
    $scope.item = Item.get({ id: 1});
    $scope.original = angular.clone(item);
    $scope.isClean = function() {
      return angular.equals($scope.item, $scope.original);
    }

    $scope.isClean(); //returns true

    $scope.save = function() {
       if($scope.isClean()) {  //is always false here
         return;
       }
       //etc..
    }
}]);
4

1 回答 1

2

我认为你有一个异步问题。这是您的代码,解释如下:

$scope.item = Item.get({ id: 1}); // Until AJAX completes, $scope.item is undefined
$scope.original = angular.clone(item); // AJAX hasn't completed yet, this is a clone of undefined

$scope.isClean(); // Compares undefined to undefined, returns true

$scope.save = function() {
    if($scope.isClean()) { // AJAX has loaded, but original is not updated. Now we're comparing an object to undefined. 

    }
}

您需要在您的上指定一个回调.get来更新原始文件,如下所示:

$scope.item = Item.get({ id: 1 }, function(res) { 
    $scope.original = angular.clone($scope.item) // Could also use 'res'
});
于 2013-05-15T17:30:54.680 回答