Sam*_*Sam 70 javascript uppercase angularjs angularjs-filter
我试过使用大写过滤器,但它不起作用.我尝试过两种方式:
<input type="text" ng-model="test" uppercase/>
Run Code Online (Sandbox Code Playgroud)
和
<input type="text" ng-model="{{test | uppercase}}"/>
Run Code Online (Sandbox Code Playgroud)
第二个触发javascript错误:
语法错误:令牌'test'是意外的,期待[:]
我希望文本在用户在文本框中键入时强制为大写.
我怎样才能做到这一点?
GHC*_*GHC 103
请参阅下面的其他答案,该答案优于此答案.
这个答案基于这里的答案:如何在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
}
};
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
Kar*_*les 67
如果有人试图在现有字符串的开头输入小写字母,则接受的答案会导致问题.每次按键后光标移动到字符串的末尾.这是解决所有问题的简单解决方案:
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");
}
};
})
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴:http: //jsfiddle.net/36qp9ekL/1710/
Tim*_*hon 35
我们的想法是在客户端将字符串显示(不转换)为大写,并在服务器端转换为大写(用户可以始终控制客户端发生的事情).所以:
1)在html中:
<input id="test" type="text" ng-model="test">
Run Code Online (Sandbox Code Playgroud)
这里没有大写的转变.
2)在css中:
#test {text-transform: uppercase;}
Run Code Online (Sandbox Code Playgroud)
如果用户输入小写,数据显示为大写,但实际上仍为小写.3)插入数据库时,将字符串转换为服务器端的大写字母.
= = = = =玩耍,可以尝试按照:
<input type="text" ng-model="test" ng-change="test=test.toUpperCase();">
<input type="text" ng-model="test" ng-blur="test=test.toUpperCase();">
Run Code Online (Sandbox Code Playgroud)
但我觉得你的情况不需要改变或改变模糊方式.
qwe*_*gor 27
您不能在ng-model上进行过滤,因为它必须是可分配的.解决方法是解析器,或简单地ng-change.
<input ng-model="some" ng-change="some = (some | uppercase)" />
Run Code Online (Sandbox Code Playgroud)
这应该工作.
one of the simple way is,
<input type="text" ng-model="test" ng-change="upper(test)/>
just do below 2 line code in your js file,
$scope.upper = function(test){
$scope.test = test.toUpperCase();
}
Run Code Online (Sandbox Code Playgroud)
这是我的小提琴http://jsfiddle.net/mzmmohideen/36qp9ekL/299/
归档时间: |
|
查看次数: |
90909 次 |
最近记录: |