0
votes

I'm trying to create a reusable directive that will simply reset my form and it's child controls to pristine using the $setPristine() method IF all the form's input controls are emptied after the user has previously interacted with them and marked them dirty.

So basically the directive would monitor all the form <input> elements and if it determines all elements are empty call $setPristine() to reset everything back to square one.

This seems kind of trivial and something I could bust out with jQuery in 5 mins but I'm just getting my feet wet with Angular and I've been stumbling around this for a couple of hours struggling with the best approach so any help or guidance is greatly appreciated!

2

2 Answers

2
votes

Edit, easier answer: Use the require or ng-require attribute on the form elements, keeping the form $pristine if there is an error.

If require is not wanted:

Note - you need angular version 1.1.x for $setPristine().

Assuming all of the ng-model's in the form are properties of the same object, you could $watch the object, loop through the properties to see if they are undefined or '' empty strings, and $setPristine() if they are.

Form HTML - all of the models are properties of input object:

<form name="form">
  <input type="text" name="one" ng-model="input.one">
  <input type="text" name="two" ng-model="input.two"><br/>
  <input type="submit" ng-disabled="form.$pristine">
</form> 

In the controller or directive, $watch the model for changes, then loop through the object, seeing if all properties are undefined or ''. (If used in the link function, you would typically use scope in place of $scope.

var setPristine = function(input){
    if (input === undefined || input === ''){
        return 0;
    }
    return 1;
}

$scope.$watch('input', function(i){
    var flag = 0;
    //loop through the model properties
    for (var obj in i){
        flag +=setPristine(i[obj]);
    }
    // if nothing in the model object, setPristine()
    if(flag===0){
        $scope.form.$setPristine();
    }
}, true)// true allows $watch of object properties, with some overhead
0
votes

Use the dirty/pristine states of the form to know if user has touched them, and a ng-pattern to know if the field is empty or not with a regexp like /.+/. Then you can just check myForm.$dirty and myForm.$error.pattern and voila!