简体   繁体   English

所需的angularJS在指令中不起作用

[英]angularJS required is not working in directive

I have an input="text" which is required. 我有一个input="text"这是必需的。

The below code is a directive for text which force user to type only numbers. 以下代码是文本指令,它强制用户仅键入数字。

By its default required warning is ON. 默认情况下,所需警告为ON。 Now the problem is if you type any keyword except numbers in the textbox, it will not type the character ( which is fine ) but the required error will disappear!!!!!! 现在的问题是,如果您在文本框中键入除数字以外的任何关键字,它将不会键入字符(很好),但是所需的错误将消失!!!! the result is a textbox with empty value and not required error message !!! 结果是带有空值的文本框,并且不需要错误消息!

 angular.module('league').directive('numbersOnly', function () { return { require: 'ngModel', link: function (scope, element, attr, ngModelCtrl) { function fromUser(text) { if (text) { var transformedInput = text.replace(/[^0-9]/g, ''); if (transformedInput !== text) { ngModelCtrl.$setViewValue(transformedInput); ngModelCtrl.$render(); } return transformedInput; } return undefined; } ngModelCtrl.$parsers.push(fromUser); } }; }); 
 <input type="text" class="CreateTxt" ng-model="league.name" name="leagueName" required /> <span ng-show="myForm.leagueName.$error.required" style="color:red">Its required...</span> 

Couldn't you achieve the same behavior with using type="number"? 使用type =“ number”不能达到相同的行为吗?

You need to change the 您需要更改

return undefined;

to

return null;

Otherwise angular will result in parse error, which is not required error. 否则,角度将导致解析错误,这不是必需的错误。 So you did almost everything good except your choice for the fallback value. 因此,除了选择后备值以外,您几乎一切都做得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM