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

Encountering the error "TypeError: Unable to access property 'findAll' of undefined" when using Sequlize

Currently, I am in the process of developing a CRUD Application utilizing PostgreSQL, Sequelize, and Express. I have been referring to this specific tutorial as my guide. However, it appears that there might be an issue with either my model or database con ...

Transpiler failed to load

My Angular application running on Node has recently encountered a problem with the transpiler. I have been trying to load mmmagic to evaluate uploaded files, but encountered difficulties in the process. While attempting to update NPM packages, I gave up on ...

Customizing Body Color in CKEditor for Dynamic Designs

I am facing an issue with CKEditor that I am hoping to find a solution for. My scenario involves using a jQuery color picker to set the background color of a DIV element, which is then edited by the user in CKEditor. However, I have observed that it is not ...

The image is failing to animate according to the PNG sequence function

Enhanced Functionality: Upon clicking the "Tap Here" image button, a function called "GameStart()" is triggered. This function ensures that the main image "Star" descends down the page from the top through an animated sequence using png logic. The propose ...

Having trouble getting your Bootstrap v4 carousel to function properly?

Currently, I have implemented the carousel feature from Bootstrap v4 in a Vue web application. I am following the same structure as shown in the sample example provided by Bootstrap, but unfortunately, it is not functioning correctly on my local setup and ...

Tips for dodging drawn-out sequences of periods

When working with nested objects using dot notation, it can be tedious to constantly check if each previous object exists. I'm looking for a solution that avoids lengthy if chains like if (a && a.b && a.b.c && a.b.c[0] ... ) ...

JavaScript file encountering a problem with its global variables

What is causing the alert("2") to pop up first instead of it being second? Why am I encountering difficulty creating global variables c and ctx? Is there a way for me to successfully create these two global variables in order to utilize ...

What is the process to activate a resize event with nvd3?

I am trying to figure out how to make the resize event trigger on nvd3 for AngularJS. The issue I am facing is that when I add line breaks in the labels of the pie chart and then resize the window, the labels revert back to a single line. What I want is ...

Troubleshooting the issue of Angular 2 error: Cannot access the 'getOptional' property

Currently, I am navigating my way through angular 2 and attempting to define a service named searchservice. I want to inject this service in the bootstap part of my project: import {SearchService} from 'src/service'; Here is the code for the Se ...

Retrieve information using PHP with AJAX without revealing it on the screen

Is it feasible to fetch data using Ajax in PHP and store them in a JS variable without displaying it? I require this data for date manipulation but do not want to show it. When I attempted to merely return the data without echoing it, the Ajax data in JS ...

Omit specific TagNames from the selection

How can I exclude <BR> elements when using the statement below? var children = document.getElementById('id').getElementsByTagName('*'); Is there a special syntax for getElementsByTagName that allows me to achieve this, or is the ...

What is the process for retrieving the AJAX response text?

When it comes to my AJAX development, I rely on prototype and utilize the following code: somefunction: function(){ var result = ""; myAjax = new Ajax.Request(postUrl, { method: 'post', postBody: postData, content ...

Prevent altering client values via developer tools

Our application is built using HTML5, the Foundation framework by ZURB, and AngularJS. We are seeking a way to prevent users from accessing and changing the values of our Angular objects (specifically scope variables) through the developer tool console. ...

Guide to showcasing JSON Array in an HTML table with the help of *NgFor

Struggling to showcase the data stored in an array from an external JSON file on an HTML table. Able to view the data through console logs, but unable to display it visually. Still navigating my way through Angular 7 and might be overlooking something cruc ...

"Utilizing AJAX to dynamically extract data from PHP and manipulate it in a multi-dimensional

Just starting out with JSON/AJAX and I'm in need of some help... I have a PHP page that seems to be returning [{"id":"1"},{"id":2}] to my javascript. How can I convert this data into something more user-friendly, like a dropdown menu in HTML? Here i ...

Fixing issues with sending a GET request using $http

Despite passing a parameter, I am unable to reach the endpoint Attempting to send an id to the endpoint for a GET request controller.js var vid = $routeParams.vidId //retrieve the video id console.log(vid) //successful $http({ ...

How can I retrieve and store session information during the authorization event in Socket.io with express-sessions?

I have set up a websocket using Socket.io and the express 4 framework on a node.js server. Currently, I am working on implementing an authorization step for my users when they are using the websocket. Upon a user connection, a token is passed as a query ...

In my VueJs project, I developed a custom button component that includes a loader feature. I initially passed the loader as a prop, but I am currently facing challenges integrating it with a method in another VueJs page

Here is an example of my component: <button class="BtnLoader btn btn-primary-contained btn-iconed btn-mobile btn-important" @click="onClick" :aria-label="label" :title="title"> <i v-if="loader" cla ...

Replacing URLs in Typescript using Ionic 3 and Angular

Currently facing some difficulties getting this simple task to work... Here is the URL format I am dealing with: https://website.com/image{width}x{height}.jpg My objective is to replace the {width} and {height} placeholders. I attempted using this func ...

How do I retrieve the HSL value for a color selected using an input of type 'color' in JavaScript?

I am faced with a creativity block and don't know where to begin. My goal is to develop functions that can manipulate the HSL values once I have access to them. Specifically, I am interested in modifying the light value, which is why I require it in ...