Show the array in the input field as an array

Check out my Plunker demo at the following link: https://plnkr.co/edit/stKf1C5UnCKSbMp1Tyne?p=preview

angular.module('listExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.names = ['morpheus', 'neo', 'trinity'];
}]);
<body ng-app="listExample">
  <form name="myForm" ng-controller="ExampleController">
  <label>List: <input name="namesInput" ng-model="names" required></label>

  <br>
  <tt>names = {{names}}</tt><br/>

 </form>
</body>

$scope.names is an array, but in the HTML input field it displays as morpheus,neo,trinity. How can we display it as ["morpheus","neo","trinity"]?

If an element is added or removed from the array in the input field, how do we update $scope.names with the new values?

Answer №1

If you want to monitor changes in an array, you can use $scope.$watchCollection, or if it's in an input field, you can utilize $scope.watch. Depending on the method of updating, you may need to apply JSON.stringify or JSON.parse:

(function(angular) {
  'use strict';
angular.module('listExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.names = ['morpheus', 'neo', 'trinity'];
    $scope.value = JSON.stringify($scope.names)
    $scope.$watch("value", function() {
        try {
          $scope.names = JSON.parse($scope.value)  
        } catch (e) {}
    })
    $scope.$watchCollection("names", function() {
       $scope.value = JSON.stringify($scope.names)
    })
    $scope.addName = function() {
      $scope.names.push('mr. anderson');
    }
  }]);
})(window.angular);

/*
Copyright 2019 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <script src="//code.angularjs.org/1.7.9/angular.min.js"></script>
  <script src="app.js"></script>
  

  
</head>
<body ng-app="listExample">
  <form name="myForm" ng-controller="ExampleController">
  <label>List: <input name="namesInput" ng-model="value" required></label>
  <button ng-click="addName()">Test</button>
  <br>
  <tt>names = {{names}}</tt><br/>
  
 </form>
</body>
</html>

<!-- 
Copyright 2019 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->

Answer №2

If you want to work with arrays using a custom directive, you can create one that includes both a formatter and parser:

app.directive('toFromArray', function(){
  return{
    require: 'ngModel',
      link: function(scope, elem, attrs, ctrl) {
        ctrl.$parsers.push(toArray);
        ctrl.$formatters.push(fromArray);

        function toArray(viewValue){       
          return viewValue && viewValue.split(',');
        }
        function fromArray(model) {
          console.log(model);
          return model.join();
        }
      }
    };
})

How to Use

<input name="namesInput" ng-model="names" to-from-array>

Check out the DEMO on PLNKR

For additional details, refer to:

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

Increase the width of the div to extend it to the right side of the

After analyzing the issue, it seems like the solution lies in extending the wrapper div to the right side of the page without any wrapping. Whenever I attempt to set the width to 100vw or 100%, the content within the div gets pushed below all the other ele ...

Ajax is able to fetch the URL without any issues, but the page is not being updated as expected. Instead,

I am currently working on implementing next/prev buttons using JavaScript, and have utilized a DynamicPage script for testing purposes. The only modification I made was to the beginning of the URL variable in pagenumber.js, although it essentially delivers ...

PHP Troubleshooting: Resolving Ajax Problems in Symfony 4

I am currently learning Symfony and attempting to integrate Ajax with Symfony. I have placed the Ajax code within a javascript block in Twig and added a simple function in the controller file to test its functionality. However, it seems that the Ajax is no ...

Using TypeScript, the fetch function cannot be assigned

Why am I encountering this TS warning? Type 'unknown' is not assignable to type 'PokemonList'.ts(2322) This issue is on line: "return e" Here is the code snippet: export interface PokemonList { count: number; next: stri ...

Issue with Protractor: The 'wait' function is not compatible with the 'element.all' method

Encountered an issue while writing Protractor automation tests. The Wait command does not properly wait for an array element. The example below illustrates the problem when attempting to wait for the first element after navigating to a webpage. var categor ...

Tips for accessing information from different sources within Vue 3

In my Vue 3 setup() method, I have an array [] stored as a constant. This array consists of X objects and represents the responses of a form. My goal is to showcase each object on a single dynamic page within our internal dashboard by using v-for in the t ...

Angular JS presents an exciting feature called Multiple Filters, which allows

I have a data representation application that displays information in table format with columns id, name, price, quantity The data is presented using ng-repeat. You can view it on this Plunker <body ng-controller="myController"> <h1>Data< ...

Switching between languages dynamically with Angular JS using $translateProvider and JSON files

I currently have a collection consisting of 6 different JSON files. en.json es.json fr.json it.json ja.json zh.json An illustration of the data present in each file is as follows (in this instance, considering en.json): { "SomeText": "Test in Englis ...

Best practices for implementing the map function with TypeScript

I'm currently working on mapping types in a DB using the Map function in JavaScript. This is my first time trying to do this, and I'm eager to learn but I've hit a roadblock. Here is the structure of the DB: const db = { data: [ { ...

Communicate crucial event prevention details using the event object in Angular

Here is an innovative approach I've discovered for passing information about whether to prevent an event: var info = { prevention: false }; $scope.$emit("nodeadd.nodeselector", info); if (!info.prevention) { $scope.addNodeCb(type, subtype); } ...

When using the <Routes> component, it will not render a component that acts as a container for multiple <Route> elements

Upon wrapping my component in <Routes>, I encountered this warning: Warning: [Categories] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment> In App.js: const App = () => ...

Exploring the animation potential of HTML5 canvas and Javascript through utilizing putImageData with animated gifs

I am interested in modifying the image data of each frame in an animated gif while it is playing in a web browser, using HTML5 canvas and Javascript. For instance, I would like to convert every frame to grayscale dynamically as the gif plays. Is this achie ...

What is the most effective method in AngularJS to ensure that a view is updated whenever the model changes?

This question is one that many people struggle with, myself included. I have tried three different solutions, but none of them seem to work consistently. Using $apply: This can force an update, but it may throw an error if called during a digest cycle. ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...

2 mistakes: (Uncaught ReferenceError: require isn't defined) & (npm ERR! script missing: start)

Issue #1: Environment Variables I am facing a problem with my JavaScript files app.js (main) and request.js. Both files are at the same level in the root directory, just like index.html. The request.js file contains process.env.APP_KEY. I attempted to i ...

What is the best way to incorporate an image that appears when a user clicks on a

My goal is to dynamically place an image exactly where a user clicks on the webpage. Currently, I have the following code, but it only adds the image at the top and continues to do so repeatedly...not appearing at the clicked location. <html> ...

Mastering the correct application of both Express's res.render() and res.redirect()

After implementing a res.redirect('page.ejs');, my browser is displaying the following message: Cannot GET /page.ejs In my routes file, I have not included the following code structure: app.get('/page', function(req, res) { ...

Place an element that exceeds 100% in size at the center

How can I center an image that is larger than its parent element? I have set the min-width and min-height to 100% so that the picture will always fill up the parent element. The issue arises when the image does not match the proportions of the parent elem ...

Having an issue with transmitting information to the database using ajax and Laravel

I am currently working on creating a drag and drop list that can be sorted. Each time an element is dropped into a new area, the order of the list should change accordingly. I am implementing this using AJAX and Laravel, but encountering an error when drop ...

The session variable fails to update across several requests

I am looking to track the number of requests sent by a browser and store it in the session. Below is the code snippet I have written: import express from 'express'; import expressSession from 'express-session'; import path from "pa ...