I find myself often repeating the following code in multiple controllers, one for each business object:
$scope.original = {name:"John"};
$scope.status = {error:false};
$scope.editMode = false;
$scope.cancel = function() {
$scope.item = angular.copy($scope.original);
$scope.editMode = false;
};
$scope.edit = function() {
$scope.editMode = true;
};
$scope.item = angular.copy($scope.original);
$scope.save = function(item) {
// do something ajax here
// if it comes back 409, mark as conflict
if ($scope.status.error) {
$scope.myForm.name.$setValidity("conflict",false);
} else {
$scope.original = angular.copy($scope.item);
$scope.editMode = false;
}
};
The problems are several:
- The above is boilerplate that gets repeated for each business object that a user can edit, which creates lots of repetition.
- I cannot guarantee that
$scope.myForm
is accessible from the$scope
, especially as other directives may have created isolated scopes around the form or input elements - Playing with the validity from within the controller seems unnatural. I get that I need to do my
resource.$save()
or other$http
activity from within the controller, but it feels like this type of direct validity setting belongs in a directive. - Directly setting the validity means that I also need to actively watch for when it is no longer invalid. In my example fiddle (below), if you set it invalid, then cancel and edit again, it remains invalid. http://jsfiddle.net/shp0e10q/2/