Is there a way for me to know when ng-options has completed updating the DOM?

I am currently working on integrating the jQuery multiselect plugin using a directive within my application. Here is the select element:

<select multiple 
        ng-model="data.partyIds" 
        ng-options="party.id as party.name for party in parties" 
        xs-multiselect="parties">
</select>

The parties model is fetched via $http. The multiselect plugin interprets the option elements within the select and creates the aesthetically pleasing multi-select feature.

Is it possible to determine when the select element has been populated with options so that I can prompt the multiselect plugin to update its data?

This is the directive I have created:

machineXs.directive("xsMultiselect", function() {
    return {
        restrict: "A",
        require: '?ngModel',
        link: function(scope, element, attrs, ngModel) {
            element.multiselect().multiselectfilter();
            scope.$watch(scope[attrs["xsMultiselect"]], function() {
                // Although I attempted watching, it did not provide a solution
                element.multiselect('refresh');
                element.multiselectfilter("updateCache");
            });
        }
    }
});

Answer №1

As mentioned in the comments, make sure to utilize

scope.$watch(attrs.xsMultiselect, ...)

I am uncertain about when the watch event is triggered compared to when ngOptions updates the DOM. If you observe that the watch event is firing too soon, consider using $evalAsync() or $timeout(). $evalAsync will run at a later time, but before the DOM is rendered. $timeout() will run after the DOM is rendered.

scope.$watch(attrs.xsMultiselect, function() {
   scope.$evalAsync(function() {
      element.multiselect('refresh');
      element.multiselectfilter("updateCache");
   });
});

Alternatively, after the DOM is rendered:

scope.$watch(attrs.xsMultiselect, function() {
   $timeout(function() {
      element.multiselect('refresh');
      element.multiselectfilter("updateCache");
   });
});

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

Is nextJS SSR the optimal solution for handling undefined variables in the window object to enable optional chaining in cases where global variables are not supported?

When using (window?.innerHeight || 420) for server-side rendering (SSR), the translation would be (((_window = window) === null || _window === void 0 ? void 0 : _window.innerHeight) || 420) However, this could result in a referenceError: window is not d ...

Add owl carousel to your npm project in any way you see fit

After struggling for a while, I finally wanted to implement owl-carousel, but couldn't figure out how to connect it using npm and webpack. The official NPM website states: Add jQuery via the "webpack.ProvidePlugin" to your webpack configuration: ...

Nested array in jQuery

Can someone verify the correctness of this array within an array declaration? If it is correct, can someone suggest how I can display or at least alert all the contents in chkArray? var chkArray = { tv_type[],screen_size[],connectivity[],features[]}; va ...

Unveiling the Secrets of AJAX Requests with Enigmatic Strings Attached to URLs

My goal is to keep track of cricket scores on scorespro/cricket by utilizing browser AJAX requests. By analyzing the network traffic in Google Chrome, I have noticed that my browser sends out requests in this format: Whenever I click on the response withi ...

Problem with implementing swipeable tabs using Material-UI in React

I'm experiencing an issue in my application with the react swipeable tabs from material-ui. I followed all the installation steps recommended in the documentation. Currently, I am encountering the error shown in the screenshot below. Could there be a ...

The information seems to not be getting transferred to the req.body variables from the HTML form

Within my server-side settings using knex and express, I have defined the following function: // POST: Create new users app.post('/add-user', (req, res) => { const {firstName, lastName, emailAdd, gender, dob, password} = req.body; cons ...

Client-side sorting in jqGrid

I'm working with a tree-grid that has autoloading rows. My objective is to sort the grid by the tree column directly on the client side. However, every time I click on the column header to sort, it triggers an unnecessary Ajax call for sorting, when ...

Dynamic Image Grid Created Using JavaScript Glitches

My dilemma involves using JQuery to create an HTML grid of images styled with Flex Boxes. The setup works perfectly on desktop, but when viewing it on mobile devices, the images begin to act strangely - jumping, overlapping, and even repeating themselves i ...

The process of passing $refs in Vue explained

I have a feature where all the data is passed to the child component. Currently, I am able to pass $attrs and $listeners successfully: <template> <el-form v-on="$listeners" v-bind="$attrs" :label-position="labelPosition"> <slot /> ...

When using Laravel 5.2, JSON data is mistakenly returned as HTML

I've encountered an issue with ajax. My goal is to fetch all the records from a specific table using this ajax call: $('#chooseInvBtn').on('click', function(){ $.ajax({ type: "POST", url ...

Enhance information flow within pages using SWR in NextJS

Utilizing SWR in a NextJS project has been a great experience for me. I have successfully fetched a list of data on my index page and added a new entry to the data on my create page. Now, I am looking to take advantage of SWR's mutate feature to updat ...

Sending a null variable via an AJAX post request from jQuery to PHP

Query: <table> <tr> <td id="percentage">Percent:&nbsp; <?php echo $percent; ?> %</td> </tr> </table> <div class="box-footer" style="float: right"> <a href="<?php echo base_url(); ?>stu ...

Swapping React components within a list: How to easily change classes

For my latest project, I am building a straightforward ecommerce website. One of the key features on the product page is the ability for users to select different attributes such as sizes and colors. These options are represented by clickable divs that pul ...

Using the scope attribute with $watch does not effectively monitor changes to the model

I'm currently developing a directive designed for <input> that monitors user input. The goal is to reformat the input model object and set a variable as true once a valid phone number has been entered. CountryISO is injected as a constant depen ...

Tips for showcasing retrieved JSON with jQuery's ajax functionality

Below is the jquery code I am working with: $.ajax({ type: "POST", url: "Ajax/getTableRecord", data:{ i : id, t: 'mylist'}, dataType: 'json', success: function(data){ alert(data); ...

Downloading PDF files with Angular

I am working with an angular function that retrieves pdf data from the server: printDocument: function (bundleId, policyId) { var fileName = "test.pdf"; var a = document.createElement("a"); document.body.appendChild(a); ...

A Step-by-Step Guide on Importing Components in Vue.js

I have defined the following component as shown below: import Vue from 'vue'; import Datepicker from 'vuejs-datepicker'; Vue.component('DatePicker', { template: ` <datepicker name="date"></datepicker> ` ...

What steps do I need to take to develop a CLI application similar to ng, that can be installed globally on the system

Upon installing npm i ng -g How does the system determine the installation path? I am interested in creating an application that can be installed and executed similarly. ...

Creating responsive D3.js charts for various screen sizes and devices

After creating a chart using d3.js, I noticed that the chart does not resize when zooming in or out on the web browser window. Below is the code snippet of what I have attempted so far: <!DOCTYPE html> <html> < ...

Error occurs in ASP.NET AJAX Control Toolkit while uploading files within Scriptresource.axd

I recently encountered an issue with my AJAX Control Toolkit File Upload (Version 15.1.4) in my ASP.Net Web Application. Up until this week, it was functioning perfectly fine. However, starting yesterday, I started receiving a JavaScript error right after ...