AngularJS and Select2's Multiple - Tags feature can display tags intermittently, showing some and hiding others as needed

Currently, I am implementing AngularJS along with select2 (not using ui-select).

In my view, the following code is present:

<select 
name="rubros" 
id="rubros" 
class="select2 form-control"
ng-model="vm.comercio.tags" 
ng-options="rubro.nombre for rubro in vm.rubros track by rubro.id"
multiple>
</select>

The select element is bound to a variable named "comercio.tags," which is an array of objects.

An interesting issue arises where at times the tags are displayed correctly, while other times they do not appear on the screen despite the binding functioning as expected.

This erratic behavior occurs randomly. Upon refreshing the browser multiple times (using F5), the error may show up and disappear unpredictably.

Here are some images for reference:

https://i.sstatic.net/1KTcv.png

https://i.sstatic.net/8s2Q4.png

https://i.sstatic.net/7J0uL.png

The tags are fetched via a GET request using $http.

It's puzzling because the issue seems to be occurring inconsistently.

Update:

Additional code requested by a helper member

//controller initialization before this

var scope = this;

var id = $routeParams.id;   //the ID of the commerce/store being edited and preloaded on the page

//variable to store the retrieved commerce/store
scope.comercio = {
    tags:[]
};

/*
    HTTP request to fetch the commerce/store with "id"
    The retrieved model has a tags property that is properly populated (as evident in the images showing input above select2, utilized for debugging)
*/

$http.get("http://localhost:8000/api/comercio/" + id).then(function (response) {

    scope.comercio = response.data.model;

},
function (response) {

    scope.comercio = null;

});

//further controller instructions and declarations

Answer â„–1

It has been pointed out that the issue stems from select2 being a jQuery plugin, requiring it to be integrated into the Angular app lifecycle through methods such as "refreshing", compiling, digesting or watching. In simpler terms, select2 needs to be connected to the AngularJS app lifecycle.

So how do we achieve this? Using a directive. While the official documentation is extensive, a concise solution can be seen in the code snippet below:

app.directive("appSelect2", function($timeout) {

    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            jQuery(element).select2();

            scope.$watch(attrs.ngModel, function () {
                $timeout(function () {
                    element.trigger('change.select2');
                }, 100);
            });

        }
    };
});

By implementing this directive and adding the "app-select2" attribute to the select2 input specified in your HTML, the integration works seamlessly.

I am immensely grateful for the assistance provided. Thank you very much.

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

Swap out the svg element with an icon alternative

Transforming Circle Elements into Shopping Cart Icons I am attempting to change the appearance of my SVG circle elements to resemble shopping carts. Is there a method to completely alter the definition of a circle element in svg so that it displays a spec ...

How to send a value to a function in Angular from a different function?

Within my Angular Typescript file, I am working with two functions named data and lists. My goal is to pass the variable windows from the function data to the function lists. However, when attempting to call the function lists, I encounter an error: Canno ...

Having trouble retrieving returned data after refetching queries using Apollo and GraphQL

I am able to track my refetch collecting data in the network tab, but I am facing difficulty in retrieving and using that data. In the code snippet below where I am handling the refetch, I am expecting the data to be included in {(mutation, result, ...res ...

In JavaScript, the JSON Object only stored the final result from a loop

I am currently working on an HTML Site that features 4 inputRange sliders. My goal is to store all values from these sliders in a nested JSON Object when a user clicks on a button. However, I have encountered an issue where my JavaScript code only saves th ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

What is the most effective method for discerning the availability of fresh data?

Many highload websites are able to notify their users of new messages or topics in real-time without the need for page refreshing. How do they achieve this and what approaches are commonly used? There appear to be two main methods: Continuously querying ...

React child component does not refresh upon modification of an array property

In my main application, I have two subcomponents that both receive the same model property. The first subcomponent deals with a number prop from model.myNumberProperty, and the second subcomponent handles an array prop from model.myArrayProperty. When ch ...

The while-loop using Regex adds only a single value to my array

Within my variable htmlContent, there lies a string filled with properly formatted HTML code, which includes various img tags. The goal is to extract each value from the src attribute of these images and place them all in an array named srcList. The issu ...

Why is the jQuery class not responding to the is(:visible) selector?

Having trouble with this issue, I created a fiddle to demonstrate what I'm trying to achieve: http://jsfiddle.net/x2btM/9/ Below is the code snippet: <div id="ZodOneDragBox"> <div id="aquariusSelectedComp1" class="killSelectedComp1" sty ...

When using Magento, pasting the same link into the browser produces a different outcome than clicking on window.location - specifically when trying to add items to the

I'm in the process of setting up a Magento category page that allows users to add configurable products directly from the category page, which is not the standard operation for Magento. After putting in a lot of effort, I have almost completed the ta ...

Is there a method to bypass the need for app.get() for each static file in express?

As I delve into using express.js, I'm faced with the task of serving numerous static files from my server - whether it's a .css, .jpg, .svg, .js, or any other file type. Is there a way to accomplish this without having to manually use app.get() f ...

Attempting to populate HTML content retrieved from my MySQL database

Currently, I am attempting to retrieve HTML content stored in my MySQL database using nodejs. The products are being retrieved from the database successfully. export async function getAllProducts() { try { const response = await fetch('ht ...

Persist the data retrieved from an asynchronous function in the memory

I am faced with a challenge in Node.js where I need to store an object in memory. This particular object is created asynchronously from an API call. The issue at hand is that previously, this object was synchronous and many parts of the application were de ...

Show HTML content from different domains within a navigation tab's content area

I am in need of showing content from a different domain on my webpage within a navigation tab. I have followed the example given in the link below: Loading cross domain endpoint with jQuery AJAX This is how my HTML code looks like: <section class=" ...

Unable to locate module named 'my'. Unable to locate controller named 'mycontroller'

https://i.sstatic.net/rrKY0.png Hey there, I'm encountering the following issue: Error : Cannot find module with name "my". Moreover, Multiple notes are popping up at this line:- Cannot find module with name my. Cannot find module with name my. ...

Error: Trying to break down a non-iterable object is not valid

Currently working on an Ionic React app and encountering the following error: Error: TypeError - Invalid attempt to destructure non-iterable instance Once I run the program, the error occurs at this point: . Shown below is a snippet of my code: import ...

ng-options do not refresh automatically when modifying elements in the array

Having trouble updating the data in a select list? It seems that when selecting 'test', the value retrieved from the API is 'ÅšlÄ…sk' even though it's not listed. For example: I select 'test' but it shows as 'ÅšlÄ ...

Preventing the display of AngularJS HTML tags while the app is being loaded

I am new to AngularJS (using version 1.5.8) and I am currently following the tutorials provided on docs.angularjs.org/tutorial. Below is the HTML code snippet: <div class="jumbotron"> <h1>{{application_name | uppercase }}</h1> ...

React revolutionizes the way we handle line breaks in

Just starting out in the world of coding and feeling a bit overwhelmed. I have checked out MDN, WJ3 but I'm still struggling with inserting line breaks into my code. return market.outcomes.map( ({ name, price ...

Unraveling functions from a JavaScript promise in a web application using ExpressJS and NeDB

I have successfully implemented code that retrieves all users from my neDB-promisses: const fetchAllUsers = (res) => { db.find({}) .sort({ name: 1 }) .exec() .then( (content) => { res.status(2 ...