Angular 1.2: Is it possible to exclude an input on form dirty checking?

前端 未结 2 1860
不思量自难忘°
不思量自难忘° 2021-02-20 00:19

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

2条回答
  •  感情败类
    2021-02-20 00:35

    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');
        }
      }
    
    }
    
    
    
    
    Company:
    Persons:

    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;
        }
      }
    }]);
    
    
    Watching dirty:
    Ignoring dirty:
    dirty: {{test.$dirty}}

提交回复
热议问题