我试过使用大写过滤器,但它不起作用。我试过两种方法:
<input type="text" ng-model="test" uppercase/>
和
<input type="text" ng-model="{{test | uppercase}}"/>
第二个触发 javascript 错误:
Syntax Error: Token 'test' is unexpected, expecting [:]
我希望当用户在文本框中键入时将文本强制为大写。
我该怎么做?
最佳答案
请看下面的另一个答案,它比这个更好。
此答案基于此处的答案:How to autocapitalize the first character in an input field in AngularJS? .
我想你想要的是这样的解析器函数:
angular
.module('myApp', [])
.directive('capitalize', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
var capitalize = function(inputValue) {
if (inputValue == undefined) inputValue = '';
var capitalized = inputValue.toUpperCase();
if (capitalized !== inputValue) {
// see where the cursor is before the update so that we can set it back
var selection = element[0].selectionStart;
modelCtrl.$setViewValue(capitalized);
modelCtrl.$render();
// set back the cursor after rendering
element[0].selectionStart = selection;
element[0].selectionEnd = selection;
}
return capitalized;
}
modelCtrl.$parsers.push(capitalize);
capitalize(scope[attrs.ngModel]); // capitalize initial value
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<input type="text" ng-model="name" capitalize>
</div>
关于javascript - angularjs 在文本框中强制大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16388562/