In the example beneath, is it possible to ignore the dirty state of the dropdown list? Now it get\'s dirty if the user changes the selected person. But I don\'t care if this fie
I don't know if you have any other input elements in your form. But in your case you could explicitely check if the company input is dirty:
function TestingCtrl($scope) {
$scope.company = '';
$scope.persons = [{
name: 'Alice'
}, {
name: 'Bob'
}];
$scope.selectedPerson = $scope.persons[0];
$scope.checkForm = function() {
var isDirty = false;
angular.forEach($scope.personForm, function (value, key) {
// Input element
if (value.hasOwnProperty('$modelValue') && value.$name!='person') {
isDirty = isDirty || value.$dirty;
}
});
if (isDirty ) {
alert('Form is dirty');
} else {
alert('Form is clean');
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<div ng-app>
<div ng-controller="TestingCtrl">
<form name="personForm" novalidate>
Company:
<input name="company" type="text" ng-model="company" required>
<br>Persons:
<select name="person" ng-options="p.name for p in persons" ng-model="selectedPerson"></select>
</form>
<br>
<button ng-click="checkForm()">Check if dirty</button>
</div>
</div>
UPDATE I have updated my solution, now you can exclude specific input fields. However each input field has to have the attribute name set
UPDATE II
A much cleaner solution would be to use a directive which prevents the form from setting the state to dirty if the value of a specific input is set. Here you have an example:
angular.module('myApp', []).directive('ignoreDirty', [function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$pristine = false;
}
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<form name="test">
Watching dirty: <input ng-model="name" /><br />
Ignoring dirty: <select ng-model="gender" ignore-dirty>
<option>male</option>
<option>female</option>
</select><br />
dirty: {{test.$dirty}}
</form>
</div>
boindiil's directive based solution works but has a flaw: it stops working if form's $setPritine
is executed manually. This can be solved by adding an extra line that wipes out the method behavior for the input:
angular.module('myApp', []).directive('ignoreDirty', [function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$setPristine = function() {};
ctrl.$pristine = false;
}
}
}]);