AngularJS validity not reset once $setValidity called

angularjs

I have this element:

<input type="text" name="azurerepo" 
    ng-model="item.azurerepo" 
    ng-class="{error: myForm.azurerepo.$invalid}" 
    ng-required="item.deploymentType=='azure'" 
    ui-event="{ blur : 'azureCallback()' }" />

The callback does:

$scope.myForm.azurerepo.$setValidity('azurerepo',false);

If I type data and come out of the input it sets it invalid.

If I go back into the input, backspace all the entered data and then type something its still invalid! I would expect it to be valid now because data has been typed in.

Best Solution

I don't know why you decided to use angular-ui instead of creating simple directive, nevertheless I suppose it's possible to add keyup event to ui-event directive and call function to set validity true here.

But I'd rather recommend you to keep it simple with custom directive:

yourApp.directive('checker', function () {
  return {
    restrict: 'A',
    scope: {
        checkValidity: '=checkValidity' // isolate directive's scope and inherit only checking function from parent's one
    },
    require: 'ngModel', // controller to be passed into directive linking function
    link: function (scope, elem, attr, ctrl) {
        var yourFieldName = elem.attr('name');

        // check validity on field blur
        elem.bind('blur', function () {
            scope.checkValidity(elem.val(), function (res) {
                if (res.valid) {
                    ctrl.$setValidity(yourFieldName, true);
                } else {
                    ctrl.$setValidity(yourFieldName, false);
                }
            });
        });

        // set "valid" by default on typing
        elem.bind('keyup', function () {
            ctrl.$setValidity(yourFieldName, true);
        });
    }
   };
 });

and your element:

<input name="yourFieldName" checker="scope.checkValidity" ng-model="model.name" ng-required=... etc>

and controller's checker itself:

function YourFormController ($scope, $http) {
    ...
    $scope.checkValidity = function (fieldValue, callback) {
       $http.post('/yourUrl', { data: fieldValue }).success(function (res) {
          return callback(res);
       });
    };
    ...
}
Related Question