Reputation: 9776
I have a simple angular form, like in this example.
js:
angular.module('myApp', []).controller('AppController', function($scope) {
$scope.values = {
value: 'default'
};
});
html:
<form name="form">
<div class="form-group">
<label for="input">Value</label>
<input type="text" class="form-control" ng-model="values.value">
</div>
<pre>form.$dirty = {{form.$dirty}};</pre>
</form>
I want to track dirty of my from and set form state to pristine when values returned back to original.
Is there a way to say angular that this is an original value, and form dirty only with values that not equal this one?
In my example I want to see from.$dirty = true
when user types something and then enter default
back.
Upvotes: 2
Views: 1678
Reputation: 9776
If there is no another solutions I have written the following directive which allow to to do it declarative way.
directive:
angular.module('myApp').directive('trackValue', function() {
return {
require: 'ngModel',
link: function(s, e, a, ngModelCtrl) {
ngModelCtrl.$setOriginalValue = function(value) {
ngModelCtrl.$originalValue = angular.copy(value);
}
ngModelCtrl.$parsers.push(function(value) {
if(angular.equals(value, ngModelCtrl.$originalValue)) {
ngModelCtrl.$setPristine();
}
return value;
});
}
}
});
Then you can save value and changes into form should be compared with it.
$scope.form.value.$setOriginalValue($scope.values.value);
I've updated my plunker where I got desired behavior with this directive. You can change input value to anything, but when you type default
again, input state will be reset to pristine
Upvotes: 2
Reputation: 25807
You can write something like this:
$scope.$watch('values.value', function (newValue) {
if (newValue === 'some-default-value) {
this.formName.$setPristine();
}
}
Upvotes: 0