How can I set up multiselect values in AngularJS ui-select?

Solution:

Success! I managed to resolve the issue by implementing this solution and creating a customized build of the ui-select. Hopefully, this fix will be incorporated into the official master branch soon!

Issue

Is there a way to set up a select element with multiple pre-selected values? I've attempted to do so, but the selected items are not appearing in the dropdown.

Initially, I suspected that the problem was related to asynchronously retrieved data via HTTP get requests. However, even a "static" plunker example created to illustrate the situation failed to display the selected items.

My assumption is that the discrepancy arises from obtaining data from two distinct sources, resulting in mismatched indices and references between the arrays. The list of categories is fetched through one service, while the chosen categories originate from another service, returning them along with the associated dataset. Loading all 45k users in a separate select just to pick the selected ones from such a vast list would be highly impractical.

So, how can I ensure that my existing selection data is correctly displayed in the ui-select component?

Plunker link.

HTML

<body ng-controller="MainCtrl">
        <label>Assigned Categories</label>
        <ui-select
            multiple
            ng-model="categories.selected"
            on-select="selectCategory($item, $model)"
            on-remove="deselectCategory($item, $model)">
            <ui-select-match placeholder="Select Category...">{{$item.name}}</ui-select-match>
            <ui-select-choices
                repeat="category in categories.categories track by category.id">
            {{category.name}}
            </ui-select-choices>
        </ui-select>
        <pre>{{categories | json}}</pre>
</body>

JS

var app = angular.module('plunker', [
  'ui.select'
]);

app.controller('MainCtrl', function($scope) {
        $scope.categories = {
            selected: [
        {
          "id": "1",
          "name": "Foo"
        }
            ],
            categories: [
        {
          "id": "1",
          "name": "Foo 1"
        },
        {
          "id": "2",
          "name": "Bar 2"
        },
        {
          "id": "3",
          "name": "FooBar 3"
        }
            ]
        };
});

Answer №1

To properly set up the select or ui-select, as well as any other input using ng-model, you need to assign the ViewModel variable bound to the ng-model with the desired selected value or object.

In the example provided, it appears that you attempted to do so, but encountered an error because when selecting an object, your ViewModel should reference the same object (by its reference). Instead, you ended up creating a new object with identical content.

Therefore, $scope.categories.selected should be an array containing the actual objects:

$scope.categories = {
    categories: [
        {
            "id": "1",
             "name": "Foo 1"
         },
         {
             "id": "2",
              "name": "Bar 2"
          },
          {
              "id": "3",
               "name": "FooBar 3"
           }
     ]
 };

$scope.categories.selected = [$scope.categories.categories[0]];
 

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

What are the best practices for utilizing "async/await" and "promises" in Node.js to achieve synchronous execution?

I'm fairly new to the world of web development and still grappling with concepts like promises and async/await. Currently, I'm working on a project to create a job posting site, but I've hit a roadblock trying to get a specific piece of code ...

Switch up the sequence of selected/appended SVGs in D3

In this dot matrix visual example, different colored circles represent funding percentages from three countries: USA, Canada, and Mexico. The gray circles indicate the remaining funding to be raised. The code snippet showcases how the circles are mapped ba ...

Add information to the Database seamlessly without the need to refresh the page using PHP in combination with JQuery

Check out my code below: <form action='insert.php' method='post' id='myform'> <input type='hidden' name='tmdb_id'/> <button id='insert'>Insert</button> <p i ...

The MVC framework coupled with a robust Javascript/JQuery validation library is a winning

Currently, I am involved in a project that utilizes MVC 2.0 along with Kendo UI. Our team has made the decision to utilize AJAX validation instead of MVC Model level validation. This means that validation occurs during most "onchange" events on HTML contro ...

Consolidate HTML project into a unified HTML file

In my current project, I am working with a static HTML report that is organized in the structure outlined below: 1.css 2.font 3.js 4.pages 5.attachments 6.index.html I would like to know how I can combine all these elements to create a unified 'repor ...

How can I integrate NIB into a project created with WebStorm 8 using node.js, Express, Jade, and Stylus?

Starting off with node.js, Express, Jade, Styl and NIB in WebStorm 8 has been a bit of a challenge. Unfortunately, WebStorm does not natively support NIB, so I have been looking into how to manually add it. Here is the sample app.js generated by WebStorm: ...

What could be causing my array to be misconverted into JSONP data?

let defaultPosts = new Array([]); defaultPosts[0] = "first post"; defaultPosts[1] = "second post"; defaultPosts[2] = "third post"; The array in the console is showing ["first post", "second post", "third post"]; let jsonString = JSON.stringi ...

Transform the arrow function into a standard JavaScript function

Here is the React return code snippet I'm working with: return ( <div className='App'> <form onSubmit={this.submit.bind(this)}> <input value={this.state.input} onChange={(e) ...

Node.js is the perfect platform for streaming videos effortlessly

I'm attempting to live stream a video from my server, but it seems like I may be doing something wrong: Here is how my routes are defined: var fs = require('fs'); router.get('/', function(req, res) { fs.readdir(__dirname + &ap ...

Combining Two Collections in Mongoose using Node.js

As a beginner in MEAN Stack, I am currently working on a Node Js application. I have created two collections: var personSchema = Schema({ _id: Number, name: String, age: Number, stories: { type: Array, ref: 'Story' } }); va ...

Utilize the require node module to access and read JSON files within a specific folder

I'm currently working on a project where I need to read multiple JSON files using a loop in my application. The code snippet below shows how I successfully read a single file: const translations = require("../data/hello" + fileEndWith); However, th ...

Creating an Angular directive that shares a single scope while displaying multiple behaviors

I am facing a specific scenario with my directive where the refresh scope needs to be either an object or a function. How can I properly assign this to my directive? 1. Initial scenario <!--HTML--> <directive refresh="vm.refresh"> </dir ...

Can I apply a universal babel configuration across all of my personal projects?

It becomes tedious to duplicate the same configuration file for each new project I start. ...

using app.use to directly pass arguments without delay (NODE.JS)

I'm currently figuring out why the code 1 is functioning properly, while the code 2 is not... app.js: // Implementing Routes var server = require('./routes/server'); app.use('/', server); Route.js: var express = require(&a ...

Is there a way to find keys with matching values within a dictionary?

In my dictionary, I have two sets of identical array values for different keys. My query is: How can I determine which keys have the same value based on inputting just one value? I want to retrieve all keys that share the same values as an output. This i ...

Unable to execute JavaScript function by clicking

I've tried everything, but I can't seem to change the button text when selecting an item in the "Requirements" dropdown. You can view the issue on this site. Located at the bottom of the page is the "Requirements" dropdown. Each item has an oncl ...

Redirect link depending on JSON callback information

I experimented with utilizing JavaScript to automatically redirect website visitors based on their country. The code snippet below demonstrates how the visitor's IP is checked to determine their country, such as CN for China, and then redirects them ...

Troubleshooting automatic login problem in VB 2013 settings

For my application, I am utilizing the most recent version of Awesomium's WebControl. The goal is for it to automatically log in when it reaches "accounts.google.com/ServiceLogin" by executing some Javascript. In my.settings.java file, I have the foll ...

Is there a way to remove specific items from my array in Vue.js?

Essentially, I am using an HTML select element that is populated with arrays of registered users. <label > <b> <i style="opacity:0.8">Users:</i> </b> </label>&nbsp;&nbsp; <select class=&quo ...

Implementing Date.now() as a Schema Field Type in Meteor's Simple-Schema

Within my Meteor application, I have utilized Date.now() to generate a timestamp for inclusion in a new MongoDB document. Although Date.now() appears to be an appropriate choice for my app, I lack expertise in managing dates and times. As I transition to ...