【问题标题】:How to convert text to uppercase while typing in input field using angular js如何在使用angular js输入输入字段时将文本转换为大写
【发布时间】:2014-10-02 11:29:27
【问题描述】:

我知道使用 jquery 可以做到这一点,但我不知道如何使用 angular js 来做到这一点,请问有什么建议吗?

       function mayuscula(campo){
            $(campo).keyup(function() {
                           $(this).val($(this).val().toUpperCase());
            });
       }

【问题讨论】:

标签: angularjs-directive


【解决方案1】:

你也可以为此创建一个指令!

检查代码:

directive('uppercase', function() {
return {
    restrict: "A"
    require: "?ngModel",
    link: function(scope, element, attrs, ngModel) {

        //This part of the code manipulates the model
        ngModel.$parsers.push(function(input) {
            return input ? input.toUpperCase() : "";
        });

        //This part of the code manipulates the viewvalue of the element
        element.css("text-transform","uppercase");
    }
};
})

关于它的用法,这里有一个例子:

<input type="text" ng-model="myModel" uppercase />

【讨论】:

  • 您的解决方案很优雅,但遗憾的是不能很好地与指令集成:ng-pattern
【解决方案2】:

您可以在 HTML 模板中或通过 JS 使用 angular uppercase 过滤器来实现。

<div>
  <label>Input 1</label>
  <input type="text" ng-model="first">{{ first | uppercase }}
</div>

如果您需要就地更改值,请在更改值时使用toUpperCase

<div>
  <label>Input 1</label>
  <input type="text" ng-model="first" ng-change="text = text.toUpperCase()">
</div>


以上是首选方法。这是使用$watch 实现相同结果的另一种方法,但不建议这样做。参见 cmets 部分。
<div>
  <label>Input 2</label>
  <input type="text" ng-model="second">
</div> 

var unwatch = $scope.$watch('second', function(val) {
    $scope.second = $filter('uppercase')(val);
}, true);

$scope.$on('$destroy', unwatch);

相关Plunker在这里http://plnkr.co/edit/susiRn

【讨论】:

  • 我在接受(且唯一)答案时匿名投反对票,没有评论。这总是很好!
  • (广泛)使用观察者 1) 对角度性能有负面影响 2) 使逻辑流程更加复杂。因此,指令是解决此问题的更好方法,
  • 真实数据。我将我的答案更新为不推荐的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
相关资源
最近更新 更多