Divide a string into various text boxes

Is there a way to allow users to edit the value of a field that is Vertex 3D? The stored value is in string format, but I want to present it to the user as three separate input fields for easier editing.

I am looking for a method to split the string by spaces and display each index in a separate input field. I attempted to use a filter for this purpose:

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"/>
However, as filters cannot be assigned a value, it results in an error being thrown.

What would be the correct approach to achieve this functionality? Any advice is greatly appreciated!

Answer №1

If you want to display parts of a string in separate inputs, consider splitting the string by spaces:

Angular variables

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

HTML inputs

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

Give it a go on JSFiddle.

Answer №2

Here is a solution:

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 value for model: {{coordsString}}
    </div>
</div>

Answer №3

Enhancing readability and efficiency, it would be beneficial to implement a structure similar to the following:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"The issue of a malfunctioning selected option in a select dropdown within an AngularJS application

I've been experiencing some odd behavior with my Dropdown control in an AngularJS application. The selected="selected" attribute doesn't seem to be working, resulting in blank default selected values. Additionally, I'm having trouble with t ...

The object model being utilized in Angular Formly remains static even after I attempt to reassign it

Using formly, I am able to modify objects retrieved from a server. After making the necessary edits, I save the changes. However, when the server sends back the updated object, I update my model object in formly with this new data. Strangely though, formly ...

The AngularJS routing template fails to load

I am currently working on the app.js file: 'use strict'; var app = angular.module('app', [ 'auth0', 'angular-storage', 'angular-jwt', 'ui.router', 'Environment', ...

Switching the background color of alternating divs in reverse order: a step-by-step guide

I am looking to alternate the background color of divs between odd and even, with the last div being grey and the second to last div being green. I have tried using the odd/even classes in CSS, but it did not work as expected. .main{ width:500px; height ...

When I press the single quote, the submit button becomes disabled and stops working

image: https://i.sstatic.net/nKCTk.jpg result: https://i.sstatic.net/PE4oN.jpg When I press the '(single quote) key on my keyboard, the submit button (reply button) is not being disabled as expected. I simply want it to be disabled in order to pre ...

AngularJS default ngOptions for parent and child models

Is there a way to set default ngOptions through parent/child models? Here, the OP demonstrates using ngOptions with parent/child relationships. template <select ng-model="x.site" ng-options="s.site for s in data"></select> <select ng-mode ...

Troubleshooting issues with TypeScript D3 v4 module import functionality

As I embark on the journey of creating a miniature JS library using D3 to visualize line charts, I find myself navigating unfamiliar waters. However, I believe that deep diving into this project is the most effective way for me to learn. Below is the cont ...

"Encountered an error while trying to fetch a PHP file using AngularJS $http.get - Error message

I am currently working with the file api.php which fetches necessary data from a database. require_once 'db.php'; $con = mysql_connect($host,$user,$pass); $dbs = mysql_select_db($databaseName, $con); $query=mysql_query("SELECT * FROM $tableName" ...

Utilizing the map() function to parse a Json object

Looking for guidance with working with a JSON object structured like this: {"Title":"asb","Date":"2019","Other":"not important"} How can I correctly read this object and render it in <ul><li> format? Please Note: I have attempted to assign th ...

The keyboard fails to open when trying to input text on a WKWebView

Is there a way to programmatically open the keyboard in a WkWebView for tel text input after a JavaScript function call? I want the keyboard to display for efficiency reasons when a certain input is activated, but it doesn't gain focus automatically. ...

Encountering an undefined value from state when implementing useEffect and useState

One issue I am facing is that the state of my projects sometimes returns as undefined. It's puzzling to me why this happens. In the useEffect hook, I have a function that fetches project data from an API call to the backend server. This should return ...

"Can you send multiple variables using an Ajax post by using a loop

I'm trying to figure out how to post multiple variables from dynamically generated "username" ids like "username1", "username2", and so on, all in one ajax post request. The issue I'm facing is mainly with the data parameter. var numOfInputs = $ ...

Dealing with the percentage sign in table names during data retrieval

When using React and Express to retrieve and store data in JSON format, what is the correct way to reference tables that have a percentage sign in their name? componentDidMount() { // Retrieve data from http://localhost:5000/citystats, sort by ID, t ...

What could be causing the lack of response from XMLHttpRequest?

I am attempting to retrieve results from a PHP file that is connected to a database. However, the variable being sent to the database is not being sent from the XMLHttpRequest. Below is the HTML code: <input type="text" id="name"/> Here is the cor ...

What occurs when an organization's npm has numerous versions accessible?

As someone who is just starting to version a library, I would like some clarification on how npm works. I am in the process of creating a library and want to publish it to my organization's npm registry. I currently have an alpha release available in ...

Testing the ui-router with an incorrect route for unit testing

After finding a helpful post on Stack Overflow about adding unit tests for ui-router, I decided to implement the following test: describe 'State: myApp', -> # Loading the module of the filter beforeEach module 'myApp' $rootS ...

An issue arises when attempting to initialize an AngularJS global variable using a REST service

I am looking to establish a global variable called httpTimeout that will be initialized at the beginning. This variable will contain a Long value retrieved from a synchronous Rest Service call and will be utilized in various services. ( function () { &apo ...

The React application is experiencing difficulty selecting CSS files through the code

I've encountered an issue with my React app where the button.css file is not rendering properly even though I've kept both the buttn.css and button.js in the same folder. Button.css .Button { background-color: transparent; border: none; ...

Manipulate Attributes in Javascript

Having an issue here - I'm trying to use JavaScript to set some attributes. for(i=0;i<div_navi.childNodes.length;i++){ if(div_navi.childNodes[i].nodeName =="SPAN"){ div_navi.childNodes[i].setAttribute("onclick","g ...

The issue of a false value not being correctly matched in Jasmine is causing problems

Currently, I am utilizing the following code to evaluate an element with aria-checked="false". expect((accessPolicyPage.listSelectAll).getAttribute("aria-checked")).toEqual("false"); The output is presenting as Expected [ 'false' ] to equal &ap ...