问题描述:

I have a function inside of a controller that tells me wether or not a resource has been changed, so that a server request will only be sent to save the object if there have been no changes. when the is clean function is called initially, it works fine. However, when it is called inside of another function, which is triggered by an ng-click event, I get a different result. Why would this be the case?

Example Code

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..

}

}]);

网友答案:

I think you have an asynchronous problem. Here's your code, explained:

$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. 

    }
}

You need to specify a callback on your .get to update the original, like so:

$scope.item = Item.get({ id: 1 }, function(res) { 
    $scope.original = angular.clone($scope.item) // Could also use 'res'
});
相关阅读:
Top