angularjsangularjs-directiveangularjs-filterangularjs-formsangular1.6

Exclude control from affecting form $pristine


I have a text input within a directive that I want to use as a filter for displaying a list of items, but I don't want the entering of a filter to affect the containing forms $pristine value so that entering a filter doesn't enable the save and show the Reset. How do I do this in angularJS (1.6.x)?

directive template

<form name='myForm'>
    <input placeholder="Filter" class='form-control' type='text' ng-model='vm.searchText'>
    <ul><li ng-repeat='item in vm.list | filter:vm.searchText'/></ul>
    <div>
        <br>
        <button class='btn btn-primary' ng-click='vm.save()' ng-disabled="myForm.$pristine || frmCrm.$invalid">Save</button>
        <div class='pull-right'>
            <button class='btn btn-warning' ng-click="vm.reset()" ng-hide="myForm.$pristine">Reset</button>
        </div>
    </div>
</form>

Yes I know I could easily put the filter input outside the form in this example, but in my actual situation that isn't feasible as I have nested forms and one that wraps basically the whole page.

here's plnkr example: http://plnkr.co/edit/y1dJLPbyvlZuIW1f7ey9


Solution

  • You can override the $setDirty and $setPristine methods of the ngModel:

    angular.module('xyz').directive('dontCheck', function() {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
          //set to empty functions
          ngModelCtrl.$setPristine = angular.noop;
          ngModelCtrl.$setDirty = angular.noop;
        }
      }
    });
    

    I've forked your plunker, you can try the solution: http://plnkr.co/edit/6UVTQjJtwu4mOXVt7sPT?p=preview

    Edit: Updated plunker to follow your code style. I will leave the code here as is.