繁体   English   中英

将字符串拆分为多个文本输入

[英]Split a string into multiple text inputs

我需要一种让用户编辑Vertex 3D字段值的方法。 该值存储为字符串,但我想将其作为三个单独的输入字段显示给用户,以便他们进行编辑。

我需要一种用空格分割字符串的方法,然后在单独的输入中显示每个索引。 我尝试使用此过滤器,如下所示:

 myApp.filter('split', function() { return function(input, splitChar, splitIndex) { return input.split(splitChar)[splitIndex]; } }); 
 <input type="text" ng-model="value | split:' ':0"/> <input type="text" ng-model="value | split:' ':1"/> <input type="text" ng-model="value | split:' ':2"/> 

但是您不能为过滤器分配值,因此会引发错误。

什么是实现这一目标的正确方法? TIA!

我建议用空格将字符串分割开,并在输入中显示每个部分:

角度变量

$scope.myString = 'My awesome text';
$scope.arr = $scope.myString.split(/[ ]+/);

HTML输入

<input type="text" ng-model="arr[0]" />
<input type="text" ng-model="arr[1]" />
<input type="text" ng-model="arr[2]" />

在JSFiddle上尝试一下

比过滤器做这样的事更好,更易读,更快捷:

控制器:

...
let vertexParts = vertex.split(' ');
$scope.vertex3d = {x: vertexParts[0], y: vertexParts[1], z: vertexParts[2]};
....
$scope.saveVertex = function() {
    myVertexService.save([$scope.vertex3d.x, $scope.vertex3d.y, $scope.vertex3d.z].join(' '));
};
...

模板:

<label>
    X: <input type="text" ng-model="vertex3d.x"/>
</label>
<label>
    Y: <input type="text" ng-model="vertex3d.y"/>
</label>
<label>
    Z: <input type="text" ng-model="vertex3d.z"/>
</label>

您可以这样:

 var vertexApp = angular.module('vertexApp', []); vertexApp.controller('vertexCtrl', ['$scope', function ($scope) { $scope.coordsString = 'xxx yyy zzz'; $scope.coords = $scope.coordsString.split(' '); $scope.$watch('coords[0]', function () { $scope.coordsString = $scope.coords.join(' '); }); $scope.$watch('coords[1]', function () { $scope.coordsString = $scope.coords.join(' '); }); $scope.$watch('coords[2]', function () { $scope.coordsString = $scope.coords.join(' '); }); }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="vertexApp"> <div ng-controller="vertexCtrl"> <input type="text" ng-model="coords[0]" /> <input type="text" ng-model="coords[1]" /> <input type="text" ng-model="coords[2]" /> <br /> New model value: {{coordsString}} </div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM