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

Jon*_*Jon 7 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()' }" />
Run Code Online (Sandbox Code Playgroud)

回调做:

$scope.myForm.azurerepo.$setValidity('azurerepo',false);
Run Code Online (Sandbox Code Playgroud)

如果我输入数据并从输入中输出,则将其设置为无效.

如果我返回输入,退回所有输入的数据,然后键入一些仍然无效的东西!我希望它现在有效,因为输入了数据.

Kos*_*ika 8

我不知道为什么你决定使用angular-ui而不是创建简单的指令,但是我认为可以keyupui-event指令和调用函数中添加事件来设置有效性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);
        });
    }
   };
 });
Run Code Online (Sandbox Code Playgroud)

和你的元素:

<input name="yourFieldName" checker="scope.checkValidity" ng-model="model.name" ng-required=... etc>
Run Code Online (Sandbox Code Playgroud)

和控制器的检查器本身:

function YourFormController ($scope, $http) {
    ...
    $scope.checkValidity = function (fieldValue, callback) {
       $http.post('/yourUrl', { data: fieldValue }).success(function (res) {
          return callback(res);
       });
    };
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 优秀,看起来像它的工作.也不会把它添加到输入工作`ng-change ="myForm.azurerepo.$ setValidity(true);"`我不明白为什么需要它,为什么它不会在内部重置? (3认同)