Unexpected issue with AngularJS Select2 multiple feature: ng-selected not functioning as expected

I have been working with the code below to select an item if it is present in the filters:

            <div ng-repeat="category in categories.data" ng-model="div1">
            <div ng-repeat="(key, value) in category" mg-model="div1.div2">
                {{ key + ":"}}
                <select id={{key}} class="my_select"
                        data-ng-model="CategoryOption"
                        data-ng-change="updateCategories()"
                        data-ui-select2="{}" multiple >
                    <option ng-repeat="c in value"
                            ng-selected="(filters[key].length>0) && (filters[key].indexOf(c.trim()) !== -1)" >
                        {{c.trim()}}</option>
                </select>

            </div>
        </div>

However, I've encountered an issue where nothing is getting selected... I've considered using ng-model to filters.key, but this leads to a problem where selecting one element cancels out the selection in another select due to them being bound to the same model...

Given the code above, what is the best way to restore my selections when using select2 with multiple selection enabled?

Answer №1

After much trial and error, I finally found a workaround to solve my issue by making adjustments to select2.js once more.

I implemented a custom parameter:

<select id={{key}} class="my_select"
                   ng-model="select2"
                   ui-select2="{mySelection: filters[key] }" multiple >
                   <option ng-repeat="c in value track by $index"
                       value="{{c.trim()}}">{{c.trim()}}</option>
</select>

and within select2, I made the following modifications:

if(opts.mySelection && typeof opts.mySelection != undefined) {
    elm.val(opts.mySelection).trigger("change");
}

right before:

controller.$render();

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

Guide to choosing and unchoosing a div / button using angularJs

I am attempting to create a functionality where items are displayed in a div instead of a list. When an item is clicked, the background color of the div changes and the item is added to a column. Clicking on the item again will revert it back to its origin ...

Oops! The page you're looking for at /api/tasks

Whenever I try to access: http://localhost:3000/api/tasks, I keep getting a "Cannot GET /api/tasks" error message. This is my server.js: var express = require('express'); var path = require('path'); var bodyParser = require('body ...

Creating a JavaScript regular expression for formatting time input without using any external plugin

As I work on implementing a time input mask with the meridian of am|pm without using an input mask plugin, I've encountered some challenges. The input should not allow the user to start with alphabets, but my current pattern, although it works, clears ...

How can the checkers code be corrected due to a mistake?

Designed a simple game where the objective is to clear all the pieces by jumping over the checkers. However, encountering an error when attempting to remove the checker for the second time. Uncaught TypeError: Cannot read property 'theRow' of u ...

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

Enhance your webpage with dynamic styling using third-party CSS animation

Apologies for any similarity to other questions on this topic. I have searched extensively, but any assistance would be greatly appreciated. I am utilizing a new animation library from Animista to animate specific elements on a test website. Animating ele ...

Performing API requests in NextJS using Prisma on a client-side page

Currently, I am faced with a challenge in fetching data from my database on a NextJS page designated as a client page using "use client" as required by the theme I am working with. At the moment, I have a page that fetches data from the database and redire ...

What is the best way to generate bootstrap rows from this code in React JS?

In my current array of objects, I have twelve items: { data:[ { type:"tweets", id:"1", attributes:{ user_name:"AKyleAlex", tweet:"<a href="https://twitter.com/Javi" target="_blank"> ...

JavaScript refuses to execute

I am facing an issue with a static page that I am using. The page consists of HTML, CSS, and JavaScript files. I came across this design on a website (http://codepen.io/eode9/pen/wyaDr) and decided to replicate it by merging the files into one HTML page. H ...

Using Symfony2 to send AJAX request data to a form rendering controller

I am facing an issue with a Symfony Form that I need to prefill based on the previously viewed record. The goal is to provide a way to modify the record data. I reach the form page through javascript and send an ajax request to the controller responsible f ...

Finding MongoDB data using an Express route and displaying it in a Jade template

Is there a way to retrieve data from MongoDB using an express route and display it in a jade template? Below is the code snippet of my express route (express version 2.5.8): app.get('/showData',function(req,res){ db.collection('comme ...

Scrolling in iOS 8 causing flickering problem with background image

Utilizing the Supersized jQuery slider plugin to create a full-page background slider with a fade-in effect and added height for scrolling. The slider functions correctly on desktop, but upon testing on an iOS 8 iPad device, there is noticeable flickering ...

Is Next.js compatible with CSS caching?

I'm currently working on a project with Next.js (version 12.1.0) and SCSS modules. I've noticed that my CSS seems to be caching extremely aggressively, requiring me to restart the server (npm run next dev) in order to clear it. Has anyone else en ...

Using the ControllerAs syntax in conjunction with $scope methods

Currently working on incorporating the controllerAs syntax into AngularJS 1.3 Here is how I'm starting my function declarations: function() { var myCtrl = this; myCtrl.foo = foo; // Successfully implemented myCtrl.$on("foo", bar); // Enc ...

How can we modify specific values of an object using Lodash and return the updated object?

const fruits = { apple: 2, orange: 3, grape: 4, banana: 5 } My aim is to adjust the values of certain fruits while being able to reference their current values. For example: const premiumFrutis = _.doSomething(fruits, apple + 2, banana + ...

Refreshing specific iframes without having to reload the entire webpage using jQuery

As the page loads initially, a hidden iframe and other visible ones are present. When a button is clicked, one of the visible iframes needs to be hidden while another becomes visible (with its src attribute set accordingly). The goal is to achieve this wit ...

Iterating through JSON objects in JavaScript using 'Foreach'

After receiving a JSON Object from my PHP script, I am trying to extract specific data using JavaScript. { "Data":{ "Recipes":{ "Recipe_7":{ "ID":"7", "TITLE":"Wu ...

The combination of Material UI custom TextField and Yup does not seem to be functioning properly

I am facing an issue with integrating my custom TextField into my RegisterForm along with Yup validation. Whenever I use the custom TextField, I encounter a message "⚠ Champ obligatoire" after clicking on Submit, which is not the case when using a simple ...

What's the best way to add row numbers within ajax requests?

I wrote a function that retrieves values from a form using jQuery's AJAX method: function getvalues(){ var sendid = $('#id').val(); $.ajax({ type: "POST", url: "ready.php", data: {sendid} }).done(function( result ) { $("#msg").html( "worked ...

Is there a way to prevent jQuery.ajax() from displaying errors in the console?

I have set up a jQuery JSONP request to monitor the status of a resource based on its URL. In case the resource is not accessible or the server goes down, my ajaxFail() function takes care of updating the display. function fetchServerStatus(service, host) ...