【问题标题】:How to disable trimming of inputs in AngularJS?如何禁用AngularJS中的输入修剪?
【发布时间】:2013-02-19 13:13:31
【问题描述】:

我发现了一些奇怪的行为:默认情况下,角度修剪模型值。快速谷歌搜索并不能帮助我解决这个问题。我找到了ng-no-trim 指令提案,ng-trim 等等。但没有任何效果。

我在下面提供了一个代表这个问题的小 sn-p。

function Ctrl($scope) {
  $scope.text='';

  $scope.$watch('text', function (newValue) {
    console.log(newValue);
  });
}

你也可以试试这个 sn-p here

我添加了一个与模型text 同步的文本区域。但是当添加新的尾随空格或换行时,它不会对观看做出反应。

我可以做些什么来关闭这种行为?谢谢。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    有问题的指令是 1.1.1 中的新指令;您可以使用JS Bin snippet 看到它的工作原理。

    <textarea cols="30" rows="10" ng-model="text" ng-trim="false"></textarea>
    

    【讨论】:

    • 非常感谢。我已经包含了 1.1.1 版本,现在效果很好。
    • 没问题。或许值得注意的是,1.1.2 目前是最新的不稳定版本。
    • 你能再告诉我一件事吗?我添加了ng-trim='false',当我在文本区域内输入时,我需要在一些div 中复制它的内容,但是用br 替换'\n'。但是我的替换不起作用。仅在我在新行输入一个字符后才插入 BR。有什么想法吗?示例:jsbin.com/ibosub/12/edit
    • @InviS String.prototype.replace() 带有字符串参数只替换一次。使用正则表达式进行多次替换。 $scope.clone = $scope.text.replace(/\n/g, '&lt;br /&gt;');
    【解决方案2】:

    angular 1.0.x 的回退

    var app = angular.module('app', []);
    
    app.directive('ngTrim', function() {
        return {
            require: 'ngModel',
            priority: 300,
            link: function(scope, iElem, iAttrs, ngModel) {
                if (iAttrs.ngTrim === 'false') {
                    // Be careful here. We override any value comming from the previous
                    // parsers to return the real value in iElem
                    ngModel.$parsers.unshift(function() {
                        return iElem.val();
                    });
                }
            }
        }
    });
    
    angular.bootstrap(document, ['app']);
    

    http://jsfiddle.net/vXCnj/3/

    【讨论】:

      【解决方案3】:

      您可以使用 ng-trim=true/false 启用/禁用修剪选项。 参考https://docs.angularjs.org/api/ng/input/input%5Btext%5D

      【讨论】:

      • 很高兴知道。以前从未听说过这个指令!
      • 对我来说这也是新的@MartynChamberlin
      猜你喜欢
      • 2015-06-04
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多