调用$ setValidity时,AngularJS有效性不会重置

时间:2013-05-30 16:39:18

标签: angularjs

我有这个元素:

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

回调确实:

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

如果我输入数据并从输入中输出,则表示数据无效。

如果我回到输入中,请退回所有输入的数据,然后键入仍然无效的内容!我希望它现在有效,因为已输入数据。

1 个答案:

答案 0 :(得分:8)

我不知道为什么你决定使用angular-ui而不是创建简单的指令,但我想我可以将keyup事件添加到ui-event指令并调用函数来设置有效性{{ 1}}这里。

但我宁愿建议您使用自定义指令保持简单:

true

和你的元素:

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);
        });
    }
   };
 });

和控制器的检查器本身:

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