AngularJS ng-model not refreshing

One of the features in my application is a Font Awesome icon picker that allows employees to easily access different icons without having to search for their codes online.

However, I am facing an issue where clicking on an icon does not update the ng-model. To trigger the update, I have to enter another character or space for AngularJS to recognize the changes made in the input field.

You can see the problem in action in this gif: .

The code snippet I am using for the icon picker is:

editCellTemplate: function (container, options) {
    container.html('<input class="icon-picker-input edit icp icp-auto" type="text" ng-model="iconInput" /><script>$(".icp-auto").iconpicker();</script>');
    options.setValue($scope.iconInput);
    $compile(container)($scope);
}

I am utilizing a gridview from DevExtreme with a custom editCellTemplate.

If anyone has any insights on how to resolve this issue, your help would be greatly appreciated. Thank you in advance!

Answer №1

The primary issue causing your code to not function as expected is that Angular only monitors user interaction events to update the model. The icon picker you are using bypasses Angular by directly setting the input value.

To update the model, it's necessary to create a hook in the icon picker update process: when an icon is selected, either update the iconInput scope variable manually (enclosed within a $scope.$apply call) or simply trigger the 'input' event on the input element to allow Angular to capture the new value (refer to this reference).

You can try implementing something like this:

editCellTemplate: function (container, options) {
    container.html('<input class="icon-picker-input edit icp icp-auto" type="text" ng-model="iconInput" />');
    options.setValue($scope.iconInput);        
    $compile(container)($scope);

    // Avoid inline script tags, initialize the iconpicker here
    $(".icp-auto").iconpicker();

    // Listen for icon picker selections
    $(".icp-auto").on('iconpickerSelected', function(e) {
        // Trigger the "input changed" event
        $(e.currentTarget).trigger('input');
    });
}

Note that I removed the script tag from the compiled HTML as the icon picker initialization should be done in your main code. Script tags execute in the global context, which may not always be desirable.

Update : The error during compilation mentioned in your comment could be due to JQuery not recognizing the iconPicker() method, possibly because of a missing definition in your Typescript setup. At runtime, the contents of the <script> tag interpreted by Angular are treated as regular Javascript, bypassing Typescript type checking.

Refer to this solution for enabling additional methods on the JQuery interface. It is advisable to avoid placing logic inside compiled <script> elements to prevent potential issues down the line.

Answer №2

The issue you're facing is that iconpicker() updates the input without Angular recognizing the change. To resolve this, simply insert $scope.$apply() right after the function call. The problem lies in the unconventional method of including your script. The jQuery syntax you're using will only trigger the iconpicker() for the first matched element, so modifying the second row in your demo might not have the desired effect.

Instead, create a unique ID and implement the following approach:

editCellTemplate: function (container, options) {
    container.html('<input class="icon-picker-input edit icp icp-auto"' +
      ' type="text" ng-model="iconInput" id="uniqueID"/>' +
      '<script>$("#uniqueID").iconpicker();$scope.$apply();</script>');
    options.setValue($scope.iconInput);
    $compile(container)($scope);
}

...where uniqueID should be replaced with an actual unique identifier. That task is left for you to tackle.

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 there a feature in Angular similar to Vue.js's "computed property" functionality?

After mastering Vue.js, I recently dove into Angular 4 for a new project. I've found that most things in Angular are quite similar to Vue, with the notable exception of "Computed Property". In Vue, I could easily create a computed property that would ...

The mystery of why gulp-watch fails to remove files

I need help figuring out why my gulp-watch task isn't deleting files from the /dest directory when I delete them from /src. Can someone spot the issue? var watch = require('gulp-watch'); var imagemin = require('gulp-imagemin'); ...

AWS Amplify is failing to maintain the user session post a successful login

Currently, I am developing an aws-serverless application using React. My main issue lies in the authentication process with aws-amplify. The authentication works smoothly, but the session is not being preserved. During the signing-in stage: await Auth.s ...

Guide on adding the contents of non-empty <td> tags using Javascript or JQuery

My goal is to calculate the total sum of all the HTML content within <td> elements with the attribute name='gross_val'. Here are the <td> elements I am working with: <tr><td name="gross_val" align="right" title="gross_val1" ...

Using AJAX to update content based on selected value in a dropdown menu

My challenge lies in ensuring that a select box retains the selected value from a database entry and triggers an onchange event during form editing or updating. While I have successfully populated the data in the select box based on other selections, I a ...

displaying error message after calling API on Node.js express server

I'm currently working on error handling on the front end, using responses from my Express server. The process involves sending data from the front end to the Express server via a POST request. The endpoint (referenced as /endpoint below) then communic ...

Having trouble troubleshooting the jQuery button

When I click this button, it triggers an ajax call that updates the score_up value. I can't seem to figure out what's wrong. I attempted using Firebug, but it doesn't detect the JavaScript. Any help would be appreciated! Here is the jQuery ...

What causes a small variation in the image composition when displaying a PNG file with drawImage?

In the code provided, the image file named "img" was created using Gimp. This image contains a color pixel : rgba=176 99 234 167. However, when displayed in a particular context and then its composition retrieved using getImageData, there is a sligh ...

The Disabled element does not exhibit effective styling

When we include the disabled attribute in the text element, the style does not work. Can you explain why? <input pInputText [style]="{'padding-bottom':'10px','padding-top':'10px','width':'100%&apos ...

Tips for transferring the button ID value to a GET request?

I recently developed a Node.js application that interacts with a database containing student information and their current marks. Utilizing MongoDB, I retrieve the data and present it in a table within an .ejs file. index.js router.get("/dashboard", funct ...

What is the best way to account for the 'elvis operator' within a given expression?

When connecting to my data from Firebase, I noticed that using the elvis operator is essential to avoid encountering undefined errors. Recently, as I delved into creating reactive forms, I encountered an issue with a component I developed that fetches actu ...

The link function of an AngularJs directive is unable to access the attribute value

I am facing an issue with a directive in AngularJS. return { restrict: _restrict, link: function (scope, element, attrs) { $timeout(LinkPre, 0); //Calling a scoped method }, templateUrl: Con ...

Incomplete data was retrieved from the localStorage

I am currently in the process of developing a mobile application using Phonegap version 1.4.1. I have encountered an issue on iOS (running on version 5.1) where the app fails to load all data from localStorage. Upon first use of the app, I set a flag in l ...

Activating Bootstrap modal when a navigation link is clicked

Just started a site for a client and new to Bootstrap. I've got the layout down - full-width page with "Top Nav" within the nav bar, looking to create a modal effect drop-down. When clicking on "About", it should trigger the .modal function. However, ...

Verify if the user is currently active

Is there a method to determine if the user is not active? I am currently utilizing raw PHP. I would like for the user to be automatically logged out once they close the window, indicating their inactivity. I attempted implementing window.addEventListener ...

How can we control the content being displayed on our tree?

Is there a way to customize the view of our V-treeview by filtering what is displayed? By entering the beginning of an element key in the filter field input, the tree will only show elements whose keys match the input. I am working on Vue.js with the late ...

The data source is having trouble connecting to the updated JSON format due to issues with pagination

I'm utilizing pagination.js to fetch asynchronous data using the code below. $('#demo').pagination({ dataSource: 'https://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?&ap ...

Utilizing Node.js and Express to call a function twice - once with the complete req.body and once with an empty body

Trying to articulate this may be a bit challenging, but I'll give it my best shot. I have an iOS app and Android app that both access the same node.js app through their respective web views. The iOS version is able to open the node.js app without any ...

Can a file be transferred from an Electron application to an Express server by supplying the file path?

This is my current objective: A user drags and drops a file into Electron Electron uses a python script via child_process.exec to convert the file The conversion process generates a new file in the same directory as the original With knowledge of the path ...

The Bootstrap navigation bar is experiencing functionality issues when viewed on Chrome mobile browsers

I'm currently testing out the bootstrap 3 navbar feature on my meteor application, but I'm encountering some issues specifically on mobile devices. The problem seems to be that the toggle button is not showing up as expected. Interestingly, it wo ...