Organizational Research By

Surprising Reserch Topic

element not reacting to its validity change as in for form validation


element not reacting to its validity change as in for form validation  using -'javascript,angularjs,validation'

tl;dr:

Set form field validity in code using $scope.ngModel.$setValidity('required', false); after clearing field, it doesn't work unless I put this in the html: <pre>{{ngModel.$invalid|json}}</pre>   Why?



Original not tl;dr:

Before I start - most of this information is tangentially related, the core of the matter is in the last 3 code snippets, skim the rest.

I have a controller which generates a search form from a bunch of premade fields. Each field has a directive, for example:

Html for one of the fields:

<span>
    <input class="form-control input-md"
           type="text"
           ng-model="user.text"
           typeahead="l.id as l.text for l in getUser($viewValue) | limitTo: 10"
           typeahead-loading="loadingUsers"
           typeahead-on-select="select($item, $model, $label)"
           typeahead-wait-ms="350"
           ng-change="changed()"
           autocomplete="off">
<!--MAGIC HERE - SEE ELEMENT AT END OF POST WHICH FIXES PROBLEM IF INSERTED-->
</span>


This element gets its validity set from the controller, primarily in two ways, the first is through ng-change (this works fine):

            function changed() {
                // Used to set the form as valid when we empty the textbox
                if ($scope.user.text === '') {
                    $scope.ngModel.$setViewValue(null);
                    validate(!$scope.required);
                } else {
                    //some irrelevant functional validation here
                }
            }


The second is through an event (this does NOT work):

                $scope.$on(eventList.clearUserTypeAhead, function () {
                    if ($scope.ngModel) {
                        $scope.ngModel.$setViewValue(null);
                    }
                    $scope.user.text = '';
                    validate(!$scope.required);
                });


And the validation function...

            function validate(isValid) {
                $scope.ngModel.$setValidity('required', false);
            }


Anyway, this doesn't work, unless I output the validity of the field in the html like so:

Is the field invalid?{{ngModel.$invalid|json}}

Why is this happening? What's a "clean" fix? (I can solve it by inserting this useless element and hiding it, but that's cheap). I HAVE narrowed the problem down to the field. The form reacts properly to this field being valid/invalid.
    
asked Oct 13, 2015 by mcasudhir
0 votes
7 views



Related Hot Questions



Government Jobs Opening


...