Mastering Web Application

(Rick Simeone) #1
Chapter 5

Template:


<form name="userInfoForm">
...
<button ng-click="revert()" ng-disabled="!canRevert()">Revert
Changes</button>
</form>

Controller:


app.controller('MainCtrl', function($scope) {
...
$scope.user = {
...
};
$scope.passwordRepeat = $scope.user.password;

var original = angular.copy($scope.user);

$scope.revert = function() {
$scope.user = angular.copy(original);
$scope.passwordRepeat = $scope.user.password;
$scope.userInfoForm.$setPristine();
};

$scope.canRevert = function() {
return !angular.equals($scope.user, original);
};

$scope.canSave = function() {
return $scope.userInfoForm.$valid &&
!angular.equals($scope.user, original);
};
});

Try it at http://bit.ly/17vHLWX.


Here, we have a button to revert the model back to its original state. Clicking on
this button calls revert() on the scope. The button is disabled if canRevert()
returns false.


In the controller, you can see that we use angular.copy() to make a copy of the
model and place it in a local variable. The revert() method copies this original back
over to the working user model and sets the form back to a pristine state so that all
the CSS classes are no longer set to ng-dirty.

Free download pdf