Angular.js:为什么棱角等于给我不同的结果?

时间:2013-05-15 17:21:09

标签: angularjs

我在控制器内部有一个函数,它告诉我资源是否已被更改,因此只有在没有更改的情况下才会发送服务器请求来保存对象。当最初调用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..
    }
}]);

1 个答案:

答案 0 :(得分: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'
});