Javascript 如何禁用 AngularJS 中的输入修剪?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14958418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:26:40  来源:igfitidea点击:

How to disable trimming of inputs in AngularJS?

javascriptangularjs

提问by ValeriiVasin

I've found some strange behavior: angular trims model values by default. And quick googling doesn't help me to solve this problem. I've found ng-no-trimdirective proposals, ng-trimand so on. But nothing works.

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

I've provided a little snippet that represents this issue below.

我在下面提供了一个代表这个问题的小片段。

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

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

Also you could try this snippet here.

你也可以在这里尝试这个片段。

I've added a textarea that is in sync with model text. But it doesn't react for watching when add new trailing spaces or break the line to new one.

我添加了一个与 model 同步的 textarea text。但是当添加新的尾随空格或换行到新的空格时,它不会对观看做出反应。

What could I do to turn off this behavior? Thanks.

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

回答by Michelle Tilley

The directive in question is new in 1.1.1; you can see it working using JS Bin snippet.

有问题的指令是 1.1.1 中的新指令;你可以看到它使用JS Bin 片段工作

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

回答by Francis

Fallback for angular 1.0.x

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/

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

回答by Vivek Panday

You can enable/disable trim option by using ng-trim=true/false. Ref https://docs.angularjs.org/api/ng/input/input%5Btext%5D

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