Transform a delimited string and an array of objects into a new format

Is there a way to easily convert a delimited string into an array of objects with data binding functionality?

ng-list is suitable for arrays of strings. However, I have an array of objects where I want to delimit the text property for easy editing.

Works with Array of Strings:

$scope.arrayStrings = ["one", "two", "three"];
<textarea ng-model="arrayStrings" ng-list="
" ></textarea>

How can this be achieved with objects:

$scope.arrayObjects = [{
  text: "one",
  selected: true
}, {
  text: "two",
  selected: true
}, {
  text: "three",
  selected: true
}];
<textarea ng-model="arrayObjects" ng-list="
 | text" ></textarea>

Check out the demo on plunker


One approach could be using ng-list on the array of strings and then mapping it to the array of objects. Then, use a $watch to update the object array whenever the string array changes. However, this method may overwrite other properties on the object each time the array updates. (Demo in previous plunker revision)

$scope.$watch('arrayStrings', function() {
  $scope.arrayObjects = $scope.arrayStrings.map(function(s){
    return {
      text: s,
      selected: true
    }
  });
})

Update:

There seem to be issues when using ng-list even with Krzysztof's suggestion:

toString: function() { return s }

Although overriding the toString method helps initially display the set of objects, as soon as you start typing, ng-list converts the objects back into an array of strings because toString is not triggered at that point.

To clarify my objective, I want a list of editable objects with selectable titles. I aim to maintain selections even if titles change or new items are added.

Another plunker example for demonstration

Answer №1

toSting()

When working with JavaScript, the toString() method is used to represent text values. By default, this method is inherited by all objects that are descended from Object. If the toString() method is not customized in a specific object, it will return "[object type]", indicating the object type.

Customizing toSting()

In JavaScript, the `toSting() method can be customized just like any other aspect of the language.

$scope.arrayObjects = $scope.arrayStrings.map(function(s){
    return {
        text: s,
        selected: true,
        toString: function() {
            return '{text: "' + s + '"}' // This custom output will be returned instead of [object Object]
        }
    }
});

Answer №2

Although I appreciated Krzysztof's suggestion, I ran into issues trying to bind with ng-list as it only converts the array of objects into strings, overriding any objects in scope.

To resolve this, I decided to switch from ng-list to tagging libraries that offer full object support:

  • ngTagsInput
  • angular-tags
  • bootstrap-tagsinput

I implemented ngTagsInput like this:

HTML:

<tags-input ng-model="arrayObjects" display-property="text"></tags-input>

JavaScript:

$scope.arrayObjects = [
  { "text": "one"   , "selected": false },
  { "text": "two"   , "selected": false },
  { "text": "three" , "selected": false }
];

This approach assigns each object its own element where the text property is displayed, and all elements are formatted together within an input. Modifying one object updates that individual element.

See Demo in Pluner

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

I am unable to find any resolution, so to speak

Despite reading numerous posts and trying different examples on my own, I still can't grasp this particular question that has been asked many times before. My struggle lies in returning images from various folders and processing them individually in a ...

JavaScript code to generate a UTF8 string from UTF codes

I am in possession of the byte representation of UTF8, such as: 195, 156 for "Ü" (capital U Umlaut) I am struggling to generate a JavaScript-compatible string from these numbers - all my attempts have been unsuccessful. Every method I have tried has mis ...

Attempting to transmit a text message to a PHP script using Ajax

Hey there! I'm facing a challenge while trying to send a string to a PHP file using AJAX. It seems like the http.send function is not working as expected, and I suspect there might be an issue in my code. (I'm fairly new to programming) mainlin ...

Retrieve the callback arguments using sinon.spy within a JavaScript promise

During my test with mocha and sinon, I encountered an issue where I couldn't retrieve a callback value from inside a promise scope of an HTTP-request due to the asynchronous nature of promises. It seems that by the time sinon.spy checks on the callbac ...

Issue with video.js text track memory leakage (WebVTT/VTT)

I am utilizing Video Text Tracks to showcase advanced live information on top of the video. A new video is loaded every few minutes, each with its own .webvtt file (consisting of 2-3k lines). Although everything is functioning properly, there is a persis ...

Stop the Enter key from functioning as a mouse click

Whenever an element is focused on and a mouse click action can be triggered, I've observed that the Enter key functions as if you're clicking the mouse left button. This behavior is causing conflicts in other parts of my code, so I need to find a ...

Challenges with window opening function while already in fullscreen view

Unsure of what might be causing the issue, but here's the problem... My code to open a new window is as follows: var opts = 'location=0,toolbar=0,menubar=0,scrollbars=0,resizable=0,height=450,width=300,right=350'; window.open('/' ...

What is the best way to determine the count of elements in an array that have the active property set to true?

Can anyone help me figure out the most efficient way to solve this problem? (Filter, ng-repeat, or another method?) <div>Number of active items: {{product.length}} </div> //total number of items <div>Number of inactive items: {{product.l ...

Managing multiple arrays in asynchronous functions in node.js

I am facing an issue with a large array (10K) that I need to split. I tried following this method: and it worked perfectly. However, I now need to pass the separated arrays to a request function and await the response before passing it to savetodb. Could ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

The Importance of Strict Contextual Escaping in ReactJS

When making an API call, we receive a URL in the response. In Angular JS, we can ensure the safety of this URL by using $sce.trustAsResourceUrl. Is there an equivalent function to trustAsResourceUrl in React JS? In Angular, //Assuming 'response&apos ...

Unable to retrieve Vuex state within a function

Currently, I am developing a Laravel+Vue application where Vuex is used for state management. While working on form validation, everything seems to be progressing smoothly except for one particular issue that has me stuck. The problem arises when I attempt ...

Check if the value is a string and contains a floating point number; if so, parse and format the float

I need to work on formatting decimal values returned by an API that only responds with strings. The requirement is to add a leading zero but no trailing zeros to any decimal value in the string. If the value is not a float, it should remain unchanged. For ...

Prevent overlapping of nodes and edges in a D3 force-directed layout

Check out this fascinating example at http://bl.ocks.org/mbostock/1747543: In the demonstration, Mike illustrates how to prevent nodes from colliding with each other in a graph. I'm curious if it's feasible to also prevent collisions between no ...

Can the ngx-chips library be used to alter the language of chips?

Currently, I am working with the ngx-chips library and encountering a particular issue. Here is an image representation of the problem: The challenge I am facing involves updating the language of the chips based on the selection made in a dropdown menu. A ...

When a user clicks on a React listItem, the information for that specific item is displayed using

As a beginner in the coding world, I am currently learning about React and JSON. My project involves working on three interconnected panels. Specifically, I aim to showcase checklist answers on the third panel. First Panel: Displaying: All the ESN ("46 ...

Deselect the checkbox that was initially selected when an alternative checkbox option has been chosen

I am trying to implement a feature where there are 2 groups of checkbox options on the same page. Below is the code snippet: <div class="col-xs-12"> <label class="checkbox-inline"> <input type="checkbox" th:field="*{borrowerRace1}" th:val ...

What steps should be taken to prepare data for transmission to a server in a Next.js environment?

I'm in the process of creating a website that requires authentication. I am using Next (React) and typescript for web development. My objective is to make most pages ServerSideRendered or StaticHTML. However, I encountered an issue right at the begin ...

Undefined value is encountered when passing props through the Context API in a REACT application

Exploring My Context API Provider File (Exp file) import react form 'react'; import {createContext} from "react"; export const ContextforFile = createContext(); export function ContextData(props){ let rdata=props.data return( &l ...

Is it possible to integrate two calendars into the `DatePicker` component of MUI?

The <DateRangePicker/> component from MUI has a prop called calendars which determines the number of calendars displayed inside the component popup. Here is an example: If the calendars prop has a value of "3", it will look like this: https://i.sta ...