javascript 在 Angular 中,如何有效地将输入项拆分为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14233689/
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-10-26 21:06:08  来源:igfitidea点击:

In Angular, how do I efficiently split input items into an array

javascriptmodel-view-controllerangularjs

提问by George Ananda Eman

When binding input value to an ng-model like so:

当像这样将输入值绑定到 ng-model 时:

<input type="text" ng-model="array">

how do I bind the input text as an array? So if I input one, two, three, the resulting model will be [ "one","two","three ].

如何将输入文本绑定为数组?因此,如果我输入one, two, three,则生成的模型将是[ "one","two","three ].

Right now this is how I'm achieving this:

现在这就是我实现这一目标的方式:

<input type="text" ng-model="string" ng-change="convertToArray()">

And in my controller:

在我的控制器中:

$scope.convertToArray = function(){
    $scope.array = $scope.string.split(',');
}

It works fine but I don't think it's best practice because I'm making a $scope.stringvariable and then hardcoding the destination array.

它工作正常,但我认为这不是最佳实践,因为我正在创建一个$scope.string变量,然后对目标数组进行硬编码。

Is it possible to just have the input's model set into array and then have the input pass through the function before being bound to the scope?

是否可以只将输入的模型设置为数组,然后让输入在绑定到作用域之前通过函数?

回答by Mark Rajcok

ngListwill do exactly what you want.

ngList会做你想要的。

Text input that converts between comma-separated string into an array of strings.

将逗号分隔的字符串转换为字符串数组的文本输入。

回答by LPD

No. Since your input will be a string from the user, you need to manually convert it to array or any other format.

不。由于您的输入将是来自用户的字符串,因此您需要手动将其转换为数组或任何其他格式。

Similar discussion and other approach is discussed here. probably this might help. (see accepted answer in this)

这里讨论了类似的讨论和其他方法。可能这可能会有所帮助。(请参阅此中已接受的答案)

How do I set the value property in AngularJS' ng-options?

如何在 AngularJS 的 ng-options 中设置 value 属性?