javascript - AngularJS 中表单 setvalidity 的延迟

标签 javascript jquery angularjs validation

我正在使用设置表单有效性的指令。一切都相应地进行,但是自定义有效性的 bool 值不会立即返回,确切地说,它需要执行额外的按键操作。顺便说一句,我使用“element.blur”来设置自定义有效性。

这是 HTML 代码:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
      <form ng-controller="myCtrl" name="bioManagementForm" novalidate>
        <fieldset ng-repeat="bioEducation in bioEducations" data-ng-form="nestedbioEducationsForm">
          Degree: <br />
          Availability: -- {{ nestedbioEducationsForm.bio_education_degree.$error.available }}
          <input class="form-control input-form" ng-model="bioEducation.bio_education_degree" name="bio_education_degree" id="bio_education_degree" auto-complete-validation ui-items="searchDegreeItems">
          <span class="errors" id="error-bio-education-degree">
                        <span ng-if="nestedbioEducationsForm.bio_education_degree.$error.available"> * Not Available <br /></span>
                    </span>
                    School: <br />
                    Availability: -- {{ nestedbioEducationsForm.bio_education_school.$error.available }}
                    <input class="form-control input-form" type="text" ng-model="bioEducation.bio_education_school" name="bio_education_school" id="bio_education_school" auto-complete-validation ui-items="searchSchoolItems">
          <span class="errors" id="error-bio-education-school">
                        <span ng-if="nestedbioEducationsForm.bio_education_school.$error.available"> * Not Available <br /></span>
                    </span>
        </fieldset>
    </form>
  </body>
</html>

JS代码如下:

// Code goes here

var myApp = angular.module('myApp', []); 


myApp.controller('myCtrl', function($scope){
  $scope.name = "dean";
  $scope.originalBioEducations = [{}];
    $scope.bioEducations = angular.copy($scope.originalBioEducations);
    $scope.searchSchoolItems = ["Don Bosco", "JRU", "UST", "FEU"];
    $scope.searchDegreeItems = ["BSIT", "BSED", "ECE", "COE"];
});

function monkeyPatchAutocomplete() {
    // Don't really need to save the old fn, 
    // but I could chain if I wanted to
    var oldFn = $.ui.autocomplete.prototype._renderItem;

    $.ui.autocomplete.prototype._renderItem = function( ul, item) {
        var re = new RegExp( "(" + this.term + ")", "gi" );
        var t = item.label.replace(re,"<span style='font-weight:bold;color:#04508e;'>" + this.term + "</span>");
        return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + t + "</a>" )
        .appendTo( ul );
    };
} 
monkeyPatchAutocomplete();
function remove_duplicates_safe(arr) {
        var obj = {};
        var arr2 = [];
        for (var i = 0; i < arr.length; i++) {
            if (!(arr[i] in obj)) {
                arr2.push(arr[i]);
                obj[arr[i]] = true;
            }
        }
        return arr2;
    } 

myApp.directive('autoCompleteValidation', function($timeout){
        return {
            require: 'ngModel',
            scope: {
                uiItems: "="
            },
            link: function(scope, element, attrs, ctrl){
                scope.$watchCollection('uiItems', function(val){
                    items = scope.uiItems.filter(function(n){ return n != undefined });
                    element.autocomplete({
                        source: remove_duplicates_safe(items),
                        minLength:2,
                    });
                    element.bind('blur', function(){
                        _val = element.val();
                        _index = items.indexOf(_val);
                        if(_index == -1){
                            ctrl.$setValidity('available', false);
                            console.log("dean");
                        }else{
                            ctrl.$setValidity('available', true);
                            console.log("armada");
                        }
                    });
                });
            }
        }
    });

附注

该应用程序是一个通过 ng-repeat 实现的动态字段。我也使用 data-ng-form 进行动态验证。两个输入字段均由 jquery ui 自动完成运行。验证应检测字段上的值是否在数组(具有“Items”范围变量的数组)内的自动完成选择中。如果输入字段中的内容不在选项中,它应该抛出错误。

这是 plunkr 中的一个示例:http://plnkr.co/edit/2EPuhRiR9OncV8z7q018?p=preview

最佳答案

如果您想避免添加按键事件,您应该在 ngModelController 上使用 $validators 对象属性。无论如何,这是创建验证器指令的正确方法。您可能还想将更改事件添加到自动完成中,以便您可以 $setViewValue。

               scope.$watchCollection('uiItems', function(val){
                items = scope.uiItems.filter(function(n){ return n != undefined });
                element.autocomplete({
                    source: remove_duplicates_safe(items),
                    minLength:2,
                    change: function () {
                      ctrl.$setViewValue(element.val());
                    }
                });
            });
            
            ctrl.$validators.available = function (modelValue, viewValue) {
              var value = modelValue || viewValue;
              if (items) {
              var _index = items.indexOf(value);
              
              return _index !== -1;
              }
            }

骗子:http://plnkr.co/edit/pcARNdakhEouqnCIQ2Yt?p=preview

顺便说一句。不要即时创建全局变量,在名称开头添加 _ 不会使它们成为本地变量或私有(private)变量。

关于javascript - AngularJS 中表单 setvalidity 的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37427586/

相关文章:

javascript - 不使用数组方法删除数组中的第一个元素

javascript - 如何将 html 标签从 div 附加到另一个 div?

javascript - jquery-ui 工具提示功能中的选项对工具提示没有任何影响

javascript - 单击按钮时多次出现验证消息

javascript - Angular Directive(指令)中的模糊无法正常工作

javascript - 带有两个提交按钮的 Angular 模态在 "enter"上触发

javascript - 点击链接后如何跳转到页面顶部?

javascript - 需要拆分返回的 JSON 字符串,以便我可以循环 JQuery

javascript - append() 函数在网页中不起作用

javascript - angularjs - 动态更新页面上的所有指令后重新加载它们