2013-03-02 38 views
1

我已經搜尋了互聯網,試圖找出爲什麼專有的AngularJS驗證在使用jQuery.Select2和ui-select2指令時不工作 - 它是一個錯誤嗎?Angular ui-select2指令不適用於AngularJS驗證

編輯:好的我發現它只是標記輸入發生,我的選擇下拉和文本輸入工作正常。

這裏的小提琴 http://jsfiddle.net/whiteb0x/ftEHu/

HTML:

<form name="myForm" ng-controller="Ctrl"> 
    userType: <input ui-select2="version1" class="input-xlarge" type="hidden" name="input" ng-model="userType" required> 
    <span class="error" ng-show="myForm.input.$error.required">Required</span><br> 
    <tt>userType = {{userType}}</tt><br> 
    <tt>myForm.input.$valid = {{myForm.input.$valid}} wtf???????!!!</tt><br> 
    <tt>myForm.input.$error = {{myForm.input.$error}} huh????</tt><br> 
    <tt>myForm.$valid = {{myForm.$valid}} | please hand me a gun :)</tt><br> 
    <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br> 
    </form> 

的Javascript:

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

function Ctrl($scope) { 
    $scope.userType = ''; 
    $scope.version1 = { 
     tags : null 
    };  
} 

回答

18

我相信有在指導如何選擇2是經過ngModel和選擇2插件之間的值存在問題。

總之,當沒有選擇,則UI的SELECT2指令將set the model to [](空數組)標籤,因爲這是由SELECT2插件上空多選擇輸入返回默認值(參見the docs for select2數據方法)

我會後在Github上的問題,以確認這一點,但在此期間,這裏的a workaround

function Ctrl($scope) { 
    $scope.userType = null; 
    $scope.version1 = { 
     tags : null 
    }; 

    $scope.$watch('userType', function(userType){ 
    if(angular.isArray(userType) && userType.length === 0){ 
     $scope.userType = ''; 
    } 
    }); 
} 

或者你可以使用這個定製「所需的海報」迪rective驗證模型時將採取空數組考慮:

app.directive('requiredMultiple', function() { 
    function isEmpty(value) { 
    return angular.isUndefined(value) || (angular.isArray(value) && value.length === 0) || value === '' || value === null || value !== value; 
    } 

    return { 
    require: '?ngModel', 
    link: function(scope, elm, attr, ctrl) { 
     if (!ctrl) return; 
     attr.required = true; // force truthy in case we are on non input element 

     var validator = function(value) { 
     if (attr.required && (isEmpty(value) || value === false)) { 
      ctrl.$setValidity('required', false); 
      return; 
     } else { 
      ctrl.$setValidity('required', true); 
      return value; 
     } 
     }; 

     ctrl.$formatters.push(validator); 
     ctrl.$parsers.unshift(validator); 

     attr.$observe('required', function() { 
     validator(ctrl.$viewValue); 
     }); 
    } 
    }; 
}); 
+0

有沒有解決方法?我試圖保持這個項目的驗證儘可能簡單 – iamwhitebox 2013-03-02 17:27:12

+1

Stewie非常感謝你。我希望我可以大拇指這個10倍 – iamwhitebox 2013-03-03 20:36:10

+4

那麼,你的感激值得至少10個大拇指。 – Stewie 2013-03-04 01:55:55

0

用於標記,我一直在使用該解決方案針對此問題是在輸入設置ng-minlength="1"。似乎工作得不錯。