Unable to get select2 working inside ng-repeat. Check out the code snippet below

When using select2 inside ng-repeat within a modal, it works fine outside the ng-repeat. However, when placed inside ng-repeat, it appears as a simple select with options instead of a styled select2 dropdown. I have included my code snippet below. Please help me correct where I am going wrong. Thank you.

angular.module("app", []).controller("personController", function($scope,$timeout) {
      $(document).ready(function() {
      
        $timeout(function(){ 
           
            $(".js-example-basic-multiple").select2({});
            
            $scope.products_info = [ 'Jonathan', 'Nathan', 'Chris', 'Brian', 'Timothy' ];
            console.log($scope.products_info.length);
            
          });
        });
        
          $scope.triger_select2 = function(){
              $(".js-example-basic-multiple").select2({});
          }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<link href="https://cdn.jsdelivr.net/npm/select2/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2/dist/js/select2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>

<div ng-app="app">
    
    <div ng-controller="personController">
    
    
      <button type="button" ng-click="triger_select2()" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
          This button triggers select 2 after ng-repeat loaded.
        </button>

        <div class="modal fade bd-example-modal-xl" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Add Extras</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                <div class="container">
                    <div class="row">
                        
                        <div class="col-sm">
                          This is select2 outside ng-repeat. It is working fine.
                          <select class="js-example-basic-multiple" multiple="multiple" tabindex="-1">
                              <option value="all" selected="">All Days</option>
                              <option value="AL">06/09/2020</option>
                              <option value="WY">07/09/2020</option>
                              <option value="WY">08/09/2020</option>
                              <option value="WY">09/09/2020</option>
                            </select>
                           
                        </div>
                    </div> <!-- row ends -->
                    
                    <div class="row" ng-repeat="x in products_info">
                        <div class="col-sm">
                        This is select2 inside ng-repeat. It is showing as just simple select and options instead of select2.
                          <select class="js-example-basic-multiple" multiple="multiple" tabindex="-1">
                              <option value="all" selected="">All Days</option>
                              <option value="AL">06/09/2020</option>
                              <option value="WY">07/09/2020</option>
                              <option value="WY">08/09/2020</option>
                              <option value="WY">09/09/2020</option>
                            </select>

                        </div>
                        
                    </div> <!-- ng-repeat rows end -->
                    
                </div> <!-- container ends -->
                 

              </div>
              
            </div>
          </div>
        </div>
        
    </div>
</div>

I also attempted to use 'chosen', but unfortunately, it is not supported on Android devices.

Update: I found a solution by triggering select2 after ng-repeat has loaded through a function call. Alternatively, we can use a timeout function to trigger this --> $(".js-example-basic-multiple").select2({});

Thank you to everyone who helped out.

Answer №1

Good news! I discovered a solution: I was able to activate select 2 once ng-repeat loaded by invoking a function. Alternatively, we can use a timeout function to achieve this -->

$(".js-example-basic-multiple").select2({});

Check out the updated snippet in my post.

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

Trouble with triggering a jQuery event on a dynamically generated div

I have a snippet of code that generates dynamic divs with varying content on a webpage. Each of these dynamically created divs includes the class "entry". I am seeking a way to trigger a click event when any of these dynamically generated divs are clicked. ...

Modify a field in every document and nested document by using a specific query in MongoDB with NodeJS

I am struggling with a complex query that involves searching for and updating a dynamic field in multiple embedded documents within a parent document. The challenge is to avoid manual iteration through each document and ensure that the field is updated at ...

Can you elaborate on this specific JavaScript concept?

I'm not very knowledgeable about javascript. Could someone please explain this structure to me? [{a:"asdfas"},{a:"ghdfh",i:54},{i:76,j:578}] What exactly is being declared in this structure? It appears to be an array with 3 elements, correct? Each e ...

What is the best way to put together the perfect attire for Threejs shaders?

I have been experimenting with using Three.js' built-in ShaderChunks for implementing lighting and fog effects, and I decided to start by mimicking a setup from one of the ShaderLib shaders. Initially, I utilized the following code snippet: customMat ...

Dynamic JavaScript tool

Does anyone know which library is being used on the website linked here? I am working on a project similar to this and would appreciate if anyone can identify this library for me. Thank you in advance. ...

Send Ajax request following input verification

My knowledge of JavaScript is limited, but I was able to create a form that uses AJAX by copying and pasting some code. I have also implemented standard Bootstrap 5 input validation for the form. Everything was working fine until I realized that the AJAX ...

My month sorting function is designed to work efficiently, although it seems to only be effective on the first

I am currently using a combination of JavaScript and Angular to sort through my data. Initially, I attempted to filter the data by month and it worked as expected the first time. However, for some reason, it stopped functioning properly afterwards, causing ...

Objects array - does not support the 'push' function

In my code snippet, it looks like this: var result = {}; for (var i = 0; i < questions.length; i++) { if(result.hasOwnProperty(questions[i].group)) { var questionsInGroup = result[questions[i].group]; log.debug(typeof questionsInGroup); ...

Reading and extracting data from a massive XML document using Node.js

Currently, I am facing a challenge with an XML file that is quite large - exceeding 70mb. My goal is to parse this data in Node.js for potential data visualizations down the line. After giving it some thought, I decided that converting the XML file to JSON ...

Is it possible to deactivate the video feature within the Programmable Video API's P2P connection offered by Twilio?

Can we utilize the programmable video API from Twilio to initiate an audio call through a P2P connection? Our goal is to enable both audio and video calls utilizing the Programmable Video API with a P2P connection. Is this achievable? ...

The effectiveness of the module is not meeting the anticipated standards

I successfully integrated a good plugin into my hapi server, and all responses are being logged. However, when I use console.log, console.error, console.warn, and console.info, the logs are only printing as plain text instead of using the good plugin forma ...

I am struggling with clicking on Bootstrap's pagination using AngularJS

I'm still getting the hang of Angularjs. I managed to set up a pagination system, but for some reason, I can't seem to interact with it when I run my project. Take a look at this screenshot that illustrates my issue: https://drive.google.com/fil ...

Concealment Based on Surroundings

I'm currently working on implementing a new feature called 'context-based hiding' which involves hiding content based on mouse actions. I've been struggling to figure out how to create this feature and came across a website that has it ...

gulp-webpack encountered an error: The entry module could not be found. Error: module resolution failed

Whenever I attempt to run gulp scripts, it gives me the following error message: ERROR: Entry module not found Error: Unable to resolve 'C:/Users/milan/Local Sites/project-university/app/public/wp-content/themes/fictional-university-theme/js/scrip ...

What is the best way to verify if a class attribute includes a specific class or not?

Below is the code snippet provided. The code fetches all classes and then checks for the presence of the 'mat-checked' class. pmanage.no_additional_cost().last().invoke('prop', 'class').then((Class) => { let ...

What is the reason for the nesting of JSON data in AngularJS?

My service is returning a simple JSON object: { "successYN": true, "msg": "Success!", "errors": null } Within my controller, I have the following setup: app.controller('formController', function ($http, $httpParamSerializerJQLike) { v ...

Securely verifying secret and payload with HMAC in Symfony version 5.4

My current JavaScript code is executing a POST API call to my designated endpoint: const payload = { course: args, recipient: roomId }; const signature = this.calculateSignature(JSON.stringify(payload), secret); const response = await fetch(`https:/ ...

Don't forget to save the toggleClass state to local storage in jQuery so it persists after

It's a challenge to maintain the value of toggleClass after refreshing or reloading the page. I have a structured table where rows toggle visibility when clicked. To preserve these toggle values, I utilized localStorage, but unfortunately, the state i ...

Update and modify content.php directly on the samepage.php rather than through externalpage.php by utilizing either Jquery or AJAX

Is there a preferred method for loading content on the same page instead of redirecting to an external page using AJAX or JQuery? Below is an excerpt from my external.php file: $id = null; if (!empty($_GET['id'])) { $id = $_REQUEST[ ...

Managing Incorrect Assignments of MongoDB/Mongoose ObjectID in ETL Process

My ETL process transfers data from Sybase to MongoDB, involving matching a legacy id to populate the correct mongo ObjectId in the model. Initially, this method works smoothly for the first few thousand records. However, an issue arises when encountering a ...