如何在 AngularJS 的输入字段中自动大写第一个字符? [英] How to autocapitalize the first character in an input field in AngularJS?
本文介绍了如何在 AngularJS 的输入字段中自动大写第一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将 AngularJS 表单元素内输入字段的第一个字符自动大写?
How to autocapitalize the first character in an input field inside an AngularJS form element?
我已经看到了 jQuery 解决方案,但相信这必须在 AngularJS 中通过使用指令来完成.
I saw the jQuery solution already, but believe this has to be done differently in AngularJS by using a directive.
推荐答案
是的,你需要定义一个指令并定义你自己的解析器函数:
Yes, you need to define a directive and define your own parser function:
myApp.directive('capitalizeFirst', function($parse) {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
var capitalize = function(inputValue) {
if (inputValue === undefined) { inputValue = ''; }
var capitalized = inputValue.charAt(0).toUpperCase() +
inputValue.substring(1);
if(capitalized !== inputValue) {
modelCtrl.$setViewValue(capitalized);
modelCtrl.$render();
}
return capitalized;
}
modelCtrl.$parsers.push(capitalize);
capitalize($parse(attrs.ngModel)(scope)); // capitalize initial value
}
};
});
HTML:
<input type="text" ng-model="obj.name" capitalize-first>
这篇关于如何在 AngularJS 的输入字段中自动大写第一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文