Check $pristine status of ngModel without using a form

前端 未结 3 1254
攒了一身酷
攒了一身酷 2021-02-13 00:41

Am trying to figure out how to check the state of a ngModel without using a form tag. I don\'t have wrappers is just basic input element with a ngModel.

All the example

3条回答
  •  无人共我
    2021-02-13 01:29

    There are two ways:

    1. Use ng-form:

    
      
    
    

    Now you can access the model either at $scope.myForm.namein your controller or with myForm.name in your view:

    var isPristine = $scope.myForm.name.$pristine;
    

    2. Use angular.element().controller('ngModel') (Don't do this one, bad bad bad)

    Alternatively, you could hack your way around it. But this is going to be ugly, untestable, and gross:

    var elem = angular.element(document.getElementById('myElement'));
    var model = elem.controller('ngModel');
    var isPristine = model.$pristine;
    

    Edit: Your situation (per your comment) inside of a repeater

    the only difference between my example and your is that the input field is inside a ng-repeater. Thought that wouldn't matter but I guess it does.

    And now it's time to ask yourself what you're doing and why... You can still get the information you need using ng-form, but you'll need to do some crazy stuff I wouldn't recommend:

    .. commence craziness:

    // get the first child scope (from the repeater)
    var child = $scope.$$childHead;
    while(child) {
      var isPristine = child.rptrForm.$pristine;
      var item = child.item;
      if(!isPristine) {
        // do something with item
      }
      child = child.$$nextSibling;
    }
    

    It's probably time to rethink your strategy

    I'm not sure what your end goal is, but you might want to rethink how you're going about it and why. Why do you need programmatic access to $pristine in your controller? What alternatives are there? Etc.

    I, for one, would try to leverage an ng-change event and update some flag on my item in my repeater, and leave the ng-form stuff for validation:

提交回复
热议问题