Reputation: 32960
I have a project with some business rules that ultimately rely on checking whether a form at a given route is empty. When I say empty, I really mean, empty...but, regardless of whether the user may have entered information at one point then deleted it. As far as I can tell, the $pristine model property is cleared if anything is entered into a field, and remains cleared even if the field is emptied again.
I do not believe that the models being bound are a good source of "empty" in our case, as they may have some initial state, so not everything is going to be null or a blank string. That could be done, if that is the only way to handle this particular use case, but that would require manually implementing this code on each and every view, for each and every model or set of models, for each and every unique form.
Is there a simpler way of checking if a form is empty, in that the fields of the form are at their initial states (i.e. text boxes blank (regardless of whether they may have been filled out and emptied again at some point), checkboxes in their initial state (regardless of whether they may have been changed then restored to their original state manually by the user at some point), radio buttons, dropdowns, etc. all the same way)?
Upvotes: 0
Views: 10334
Reputation: 1
I guess this could be the solution you are looking for. save all your models in one single object and compare it with an empty object when the form is submitted. If both equals : you display your popup.
HTML:
<form>
<input type="email" ng-model="user.email" name="uEmail" required/>
<input type="name" ng-model="user.name" name="uEmail" required/
<button ng-click="isUnchanged(user)">SUBMIT</button>
</form>
JS:
.controller('ExampleController', ['$scope', function($scope) {
$scope.master= {};
$scope.isUnchanged = function(user) {
if(angular.equals(user, $scope.master)){
//show your popup here
}else{
//validation, submit etc.
}
};
}]);
Please have a look at the RESET function in this example "Binding to form and control state" here => https://docs.angularjs.org/guide/forms
Upvotes: 0
Reputation: 1581
For any form which has a name, you can use a combination of $invalid and ng-minlength or ng-required/required on the input to determine if the user has left the field empty. In the following example, the submit button is disabled if the user leaves the input blank by checking the model against the ng-minlength and ng-required attributes.
<form name="someForm">
<input type="text" ng-model="someName" ng-minlength="1" ng-required="true" name="someName">
<button type="submit" ng-disabled="someForm.$invalid">
</form>
Upvotes: 1