我试过使用大写过滤器,但它不起作用。我试过两种方法:
<input type="text" ng-model="test" uppercase/>
和
<input type="text" ng-model="{{test | uppercase}}"/>
第二个触发 javascript 错误:
语法错误:令牌“测试”是意外的,期待 [:]
我希望在用户在文本框中键入时将文本强制为大写。
我怎样才能做到这一点?
我试过使用大写过滤器,但它不起作用。我试过两种方法:
<input type="text" ng-model="test" uppercase/>
和
<input type="text" ng-model="{{test | uppercase}}"/>
第二个触发 javascript 错误:
语法错误:令牌“测试”是意外的,期待 [:]
我希望在用户在文本框中键入时将文本强制为大写。
我怎样才能做到这一点?
请参阅下面的另一个答案,它优于这个答案。
这个答案基于这里的答案: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>
如果有人试图在现有字符串的开头输入小写字母,则接受的答案会导致问题。每次按下键后,光标都会移动到字符串的末尾。这是解决所有问题的简单解决方案:
directive('uppercased', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(input) {
return input ? input.toUpperCase() : "";
});
element.css("text-transform","uppercase");
}
};
})
这是一个小提琴:http : //jsfiddle.net/36qp9ekL/1710/
这个想法是在客户端将字符串显示(而不是转换)为大写,并在服务器端转换为大写(用户始终可以控制客户端发生的事情)。所以:
1)在html中:
<input id="test" type="text" ng-model="test">
这里没有大写转换。
2)在CSS中:
#test {text-transform: uppercase;}
数据显示为大写,但实际上仍然是小写,如果用户输入小写。3) 插入数据库时,在服务器端将字符串转成大写。
====== 玩转,可以试试看:
<input type="text" ng-model="test" ng-change="test=test.toUpperCase();">
<input type="text" ng-model="test" ng-blur="test=test.toUpperCase();">
但我认为 ng-change 或 ng-blur 方法对于您的情况不是必需的。
您不能对 ng-model 进行过滤,因为它必须是可分配的。解决方法是解析器,或者只是 ng-change。
<input ng-model="some" ng-change="some = (some | uppercase)" />
这应该有效。
与 Bootstrap 一起使用时,只需添加text-uppercase
到输入的类属性。