-1
我有複製粘貼以下指令僅數指令發出
.directive("onlyNumber", function() {
return {
restrict: "A",
link: function (scope, element, attr, ngModel) {
element.bind('input', function() {
var position = this.selectionStart - 1;
//remove all but number and .
var fixed = this.value.replace(/[^0-9\.]/g, '');
if (fixed.charAt(0) === '.') //can't start with .
fixed = fixed.slice(1);
var pos = fixed.indexOf(".") + 1;
if (pos >= 0) //avoid more than one .
fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.', '');
if (this.value !== fixed) {
this.value = fixed;
this.selectionStart = position;
this.selectionEnd = position;
}
});
}
};
})
的問題是,當我鍵入唯一的工作,如果我填充值,它顯示所需的錯誤消息。
第二個問題是,當我輸入非數字鍵時,它將刪除值但長度計數器增加1(即1/20而不是0/20)並且不彈出錯誤。當我按提交時,我可以得到我輸入的非數字值。
@Edited
<ng-form name="nOtherFacilityForm" novalidate isolate-form flex="100" layout-padding layout layout-wrap>
<h2 class="md-title">Other Facilities</h2>
<div flex="100" class="animate-slide-up md-whiteframe-1dp white-bg" layout-padding layout layout-wrap>
<div flex="100" flex-gt-sm="25">
<md-input-container class="md-block">
<label>Almirah</label>
<input type="text" only-number name="almirah" ng-model="LibraryEquipDetails.almirah" md-maxlength="20" maxlength="20" required />
<div ng-messages="nOtherFacilityForm.almirah.$error">
<div ng-message="required">Almirah is required.
</div>
</div>
</md-input-container>
</div>
</ng-form>
和js側
$scope.saveInfo = function() {
if($scope.nOtherFacilityForm.$invalid){
angular.forEach($scope.nOtherFacilityForm.$error, function (field) {
angular.forEach(field, function(errorField){
errorField.$setTouched();
})
});
toastr.error("Please Fill All Mandatory Fields", "Alert!");
return;
}
};
當我鍵入再一次,那麼一切都很好!
能否請你也分享了HTML,從那裏是如何產生的錯誤信息,也如果可能的工作片段。 –
@NarenMurali我已更新問題並提供更多詳細信息! –