Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS validity not reset once $setValidity called

Tags:

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.

like image 872
Jon Avatar asked May 30 '13 16:05

Jon


1 Answers

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);
       });
    };
    ...
}
like image 147
Kosmetika Avatar answered Nov 11 '22 14:11

Kosmetika