像这样将输入值绑定(bind)到 ng-model 时:
<input type="text" ng-model="array">
如何将输入文本绑定(bind)为数组?因此,如果我输入 one, two, three
,生成的模型将为 [ "one","two","three ]
。
现在这就是我实现这一目标的方式:
<input type="text" ng-model="string" ng-change="convertToArray()">
在我的 Controller 中:
$scope.convertToArray = function(){
$scope.array = $scope.string.split(',');
}
它工作正常,但我认为这不是最佳实践,因为我正在创建一个 $scope.string
变量,然后对目标数组进行硬编码。
是否可以只将输入的模型设置到数组中,然后让输入在绑定(bind)到范围之前通过函数?
最佳答案
ngList将完全按照您的意愿行事。
Text input that converts between comma-separated string into an array of strings.
关于javascript - 在 Angular 中,如何有效地将输入项拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14233689/