简体   繁体   English

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

[英]Split a string into multiple text inputs

I need a way for users to edit the value of a field that is Vertex 3D. 我需要一种让用户编辑Vertex 3D字段值的方法。 The value is stored as a string, but I want to display it to the user as three separate input fields for them to edit. 该值存储为字符串,但我想将其作为三个单独的输入字段显示给用户,以便他们进行编辑。

I need a way to split the string by spaces, and then show each index in a separate input. 我需要一种用空格分割字符串的方法,然后在单独的输入中显示每个索引。 I tried doing with this a filter, like this: 我尝试使用此过滤器,如下所示:

 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"/> 

But you cannot assign a value to a filter so it throws an error. 但是您不能为过滤器分配值,因此会引发错误。

What would be the correct way to achieve this? 什么是实现这一目标的正确方法? TIA! TIA!

I would recommand to split your string by spaces and show each part in an input: 我建议用空格将字符串分割开,并在输入中显示每个部分:

Angular variables 角度变量

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

HTML inputs HTML输入

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

Try it on JSFiddle . 在JSFiddle上尝试一下

It would be better, readable and faster than filters make something like this: 比过滤器做这样的事更好,更易读,更快捷:

Controller: 控制器:

...
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(' '));
};
...

Template: 模板:

<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>

You can do like this: 您可以这样:

 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