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

Utilizing Ionic for local data retention

Seeking assistance with connecting my app to local storage in order to save data on the user's device without resetting every time the app is closed. Struggling to link local storage to an array of objects. Any guidance would be highly appreciated. Re ...

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

Encountering an issue with top-level await in Angular 17 when utilizing pdfjs-dist module

While using the Pdfjs library, I encountered an error message that reads: Top-level await is not available in the configured target environment ("chrome119.0", "edge119.0", "firefox115.0", "ios16.0", "safari16.0" + 7 overrides) /****/ webpack_exports = g ...

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

Comprehending the significance of *this* within class structures

I've got this code snippet below. class Node { constructor(value, parent, possibleChildren = []) { this.value = value; this.parent = parent; this.children = [] this.setChildren(possibleChildren); } setChildren(possibleChil ...

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

What is the most effective approach to building this function in React JS rather than the existing .map method?

Hello, I'm fairly new to all of this so please bear with me. I've been working on developing a search function for my app, but I've encountered a problem. The search function in my header component is being rendered like this in my index: &l ...

What do you want to know about Angular JS $http request?

My goal is to send a request using $http with angular js in order to retrieve a json object from google maps. $http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city&a ...

Search for an element deep within a tree structure, and once found, retrieve the object along with the specific path leading to

I created a recursive function to search for a specific object and its path within a tree structure. However, when I changed the target ID (from 7 to 10) in the function, I encountered an error: "message": "Uncaught TypeError: Cannot read ...

Incorporating an event listener for 'storage' in jQuery using JavaScript

Can anyone tell me how to achieve the same functionality as javascript addEventListener in JQuery? I have been attempting to use it with .bind(), but it seems not to recognize the "storage" keyword. When I tried using 'e' within this context, it ...

TypeScript and Next.js failing to properly verify function parameters/arguments

I'm currently tackling a project involving typescript & next.js, and I've run into an issue where function argument types aren't being checked as expected. Below is a snippet of code that illustrates the problem. Despite my expectation ...

Passing URL parameters from App.js to routes/index.js

I have a URL that looks like this: http://localhost:3000/?url=test In my Express application's app.js file, I'm attempting to extract the "test" parameter from the URL and pass it to my routes/index.js. Currently, I can easily send a static var ...

Navigating with Next.js Router: Dynamic URLs and the power of the back button

Utilizing the Router from the package next/router allows for a dynamic URL and loading of different content on the page: Router.push('/contract', `/contract/${id}`); An issue arises where the back button does not function as expected after runni ...

Ways to extract repeated value from a function?

Currently, I am working with two files. One file contains a script that generates a token, while the other file handles that token. The issue arises with the second script, as it only logs the initial token received and does not update with any new values ...

What is the best way to create a React filter utilizing the Autocomplete component from MaterialUI and incorporating state management?

I am currently in the process of creating a filter using the Autocomplete component from MaterialUI. As I select options from the dropdown menu, several things are happening: The Autocomplete automatically adds the selected options to the Chip Array. The ...

Tips for embedding svg within ion-content

My application is developed using Angularjs and ionic framework, incorporating cordova for hybrid mobile capabilities. However, when attempting to display svg content received from the backend, the expected diagram does not render properly. This is an exa ...

Customize button text in Vue using data variable conditions

There are 3 desks in a table with role IDs 2, 4, and 6. In this scenario, two tables are involved. The goal is to dynamically display a specific role name on a button based on the current user's role ID. The desired displays are: If the current use ...

Having trouble with transferring information from JQuery to PHP

Currently, I'm working on transmitting data from jQuery to PHP. Here's an excerpt of what I've done: var jsonArray = JSON.stringify(dataArray); $.ajax({ type: "POST", url: "addcar_details.php", ...

Retrieving information from Prismic API using React Hooks

I'm having trouble querying data from the Prismic headless CMS API using React Hooks. Even though I know the data is being passed down correctly, the prismic API is returning null when I try to access it with React Hooks. Here is my current component ...

The automatic refresh feature of the DataTable every 30 seconds is malfunctioning

Currently, I am implementing an application that retrieves records from a database and populates them into a dataTable using JSON. Although my app is functioning correctly, I want to refresh the table every 30 seconds and update any added or modified rows ...