簡體   English   中英

AngularJS中表單setvalidity的延遲

[英]Delay on Form setvalidity in AngularJS

我正在使用有關設置表單有效性的指令。 一切都可以正常工作,但是自定義有效性的布爾值不會立即返回,確切地說,它需要額外的按鍵。 順便說一下,我正在使用'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

如果要避免添加keypress事件,則應在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

順便說一句。 不要動態創建全局變量,在名稱開頭添加_不會使它們成為本地變量或私有變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM