2016-11-14 102 views
0

我有幾個輸入字段,我希望驗證用戶輸入,如果只是空白。我嘗試使用指令或過濾器。我不想使用$ watch,因爲輸入字段太多。我需要的是:如果用戶在輸入字段中只設置了空格,則可以使用某些函數或指令來清理此空格。 我可以用jQuery或vanilla JS做到這一點,但我更喜歡這個結果是角度的方式。AngularJs輸入字段與ng模型與過濾器問題

如果我真的錯指令或過濾

這是我的代碼:

angular.module('app') 
.directive('customSpaceValidation', ['$filter', function ($filter) { 
    return { 
     require: '?ngModel', 
     link: function (scope, elem, attrs, ctrl) { 
      if (!ctrl.replace(/\s/g, '').length) { 
       ctrl = ""; 
      } 
      return ctrl; 
     } 
    }; 
}]) 
.filter('nospace', function() { 
    return function (value) { 
     if (!value.replace(/\s/g, '').length) { 
      value = ""; 
     } 
     return value; 
    }; 
}) 

這是用HTML指令:

<input type="text" class="form-control" id="inputKey" ng-model="channel.key" customSpaceValidation data-ng-trim="false" ng-required="true" name="inputKey" required /> 

這是用HTML過濾

<input type="text" class="form-control" id="inputKey" ng-model="channel.key | filter : nospace" data-ng-trim="false" ng-required="true" name="inputKey" required /> 

Filt呃特羅例外:

ng-table-export.src.js:45 TypeError: ngModelSet is not a function 
at NgModelController.$$writeModelToScope (ng-table-export.src.js:45) 
at writeToModelIfNeeded (ng-table-export.src.js:45) 
at ng-table-export.src.js:45 
at validationDone (ng-table-export.src.js:45) 
at processAsyncValidators (ng-table-export.src.js:45) 
at NgModelController.$$runValidators (ng-table-export.src.js:45) 
at NgModelController.$$parseAndValidate (ng-table-export.src.js:45) 
at NgModelController.$commitViewValue (ng-table-export.src.js:45) 
at ng-table-export.src.js:45 
at Scope.$eval (ng-table-export.src.js:45) 

回答

1

因爲過濾是一個單向操作,而ng-model是雙向綁定,您不能使用ng-model與過濾。當在HTML中使用時,該指令必須是蛇形的,而不是駝峯形的,即custom-space-validation

要實際驗證,則需要驗證:

.directive('customSpaceValidation', [function() { 
    var RE = /^\s+$/; 

    return { 
     require: 'ngModel', 
     link: function (scope, elem, attrs, ngModel) { 
      ngModel.$validators['customSpace'] = function(modelValue, viewValue) { 
       var value = modelValue || viewValue; 
       return !RE.test(value); 
      }; 
     } 
    }; 
}]) 
+0

一個錯字,寫的 '=' 而不是 ']',糾正。 –

+0

是的,我看到了,但我希望如果字符串只是空格來刪除它們。如果字段爲空,我有一個錯誤按摩,但我不知道爲什麼當我設置空白時,窗體返回有效。 我的願望是檢查用戶輸入設置只有空格刪除它們我嘗試使用ngFocus,ng-init等 我可以用JQuery做到這一點,但我更喜歡用角度的方式。 謝謝! –

+0

對不起,它沒有在上面的問題解釋 –