"Troubleshooting the issue of Angular JS ng-click HTML being assigned via InnerHTML but not properly invoking

I am currently working on an AngularJS phonegap application. The HTML in this application consists of a blank table that is dynamically populated using JS Ajax. The Ajax request retrieves the necessary data and fills the table using innerHTML. Each button within the table has an ng-click method associated with it:

$.ajax({
   type: 'GET',
   dataType: 'json',
   url: 'SAMPLEURL'+tID,
   contentType: 'application/json;charset=utf-8',
   success: function(response){
       var reqObject = JSON.parse(response);


       var tableHtml = "";
        for(i = 1;i<reqObject.object.length; i++)
           {
             var variant = reqObject.variants[i];
               tableHtml += "<tr><td>";
               tableHtml += "<button type='button' ng-click=\"calculateQuantity();\" class='buttonStandard' id='"+variant.Id+"' style='padding:10px 15px 20px 15px; width:100%;margin-top:-10px;'>";


               tableHtml += "<div style='height:40px'><h4>"+variant.Name+"</h4></div>";
               tableHtml += "</button>";
               tableHtml += "</td></tr><tr><td><br /></td></tr>";
           }

       document.getElementById("tableSelection").innerHTML = tableHtml;

       $scope.calculateQuantity = function() {
        alert('test');
      };

   },
   error: function(xhr){
       alert('Failed to bring Variants');
   }    
});

In addition to populating the table, I have added a calculateQuantity method to the scope. The intention is for this method to display an alert with the message 'test' when a user clicks on a button. However, this functionality does not seem to be working as expected. Can anyone provide insight into what might be causing this issue?

Answer №1

When dealing with dynamically created elements, it is important to use $compile to recompile your DOM before inserting into HTML.

To do this, simply update this line:

document.getElementById("tableSelection").innerHTML = tableHtml;

to:

document.getElementById("tableSelection").innerHTML = $compile(tableHtml)($scope);

Make sure to inject $compile into your controller as well.

Please note: It is recommended to use angular.element, which is a lightweight version of jQuery, instead of document.getElementById.

angular.element(document.querySelector('#tableSelection')).append($compile(tableHtml)($scope))

Update: In addition to the above changes, it is crucial to address another issue pointed out by Jasper Seinhorst. When using jQuery ajax outside of the Angular zone, there are options to return to the Angular zone. This can be done by wrapping your code in $timeout or calling $scope.$apply() in the response of your Ajax call, along with following Jasper Seinhorst's advice.

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

Are there any ASP.NET MVC counterparts to JavaScript Generators?

As I transition my application from MonoRail to ASP.NET MVC, I am curious if there is a counterpart to brailjs and njs. In Ruby on Rails, there is a similar concept found in the PrototypeHelper JavaScriptGenerator Methods. While I currently utilize the A ...

Download our jQuery Fileupload control complete with a progress bar for free today!

Do you know of any free jQuery file uploader plugins with a progress bar? I need one for my classic-asp website. ...

Experiencing difficulties accessing the API route through Express

Every time I attempt to access /api/file, I am receiving a status code of 404. Here is the relevant code snippet: app.js : ... app.use("/api", require("./routes/users")); app.use("/api", require("./routes/file")); ...

mysql nodejs function is returning a null value

Kindly review the contents of the dbfn.js file /*This is the database function file*/ var db = require('./connection'); function checkConnection(){ if(db){ console.log('We are connected to the Database server'.bgGreen); ...

Tips for causing the JavaScript confirm alert to appear just a single time

My latest project involves creating a confirm alert that notifies users when their password is about to expire, prompting them to change it. The functionality for this alert is located in the header section of the website. Upon successful login, users are ...

Mastering data extraction from JSON using React JS (with Axios)

Being new to ReactJS and axios, I am facing a challenge. I need to iterate through JSON data and extract values where the key is a number (e.g. 0, 1, 2...). However, I am unsure how to implement this in my code since the server provides dynamic JSON data ...

The element in the data cell is a form input field

This is the content of my webpage: <input type="text" class="form-control" >id="ButonSociete"name="ButonSociete"placeholder="Societe"> <table cellpadding="0" cellspacing="0" border="0" class="display" >id="demande" width="100%"> ...

Iterate through a collection of objects and organize the data in a specific way

Within the data structure of my API response, I am attempting to iterate through an array of objects under the items key. Each value inside these objects needs to be formatted based on the corresponding format type specified in the header key. To assist wi ...

An issue with the Babel version is preventing the Express API from starting up successfully

Error! Message: [nodemon] starting `babel-node index.js` C:\Users\Zara Gunner\AppData\Roaming\npm\node_modules\babel-cli\node_modules\babel-core\lib\transformation\file\options\option-ma ...

Troubleshooting a JavaScript project involving arrays: Let it pour!

I'm a beginner here and currently enrolled in the Khan Academy programming course, focusing on Javascript. I've hit a roadblock with a project called "Make it rain," where the task is to create raindrops falling on a canvas and resetting back at ...

Error message stating: "Unable to read property 'then' as it is undefined within Angular nested promises."

I'm having trouble passing data back from a service to a controller in my AngularJS application. The service I am calling inside a factory makes an HTTP request for JSON data and then needs to modify it before returning it to the controller. However, ...

retrieve a string value from a function within a ReactJS component

I am facing an issue with returning a string from a function. Here is the function I am using: const getImage = (name) => { const imageRef = ref(storage, name); getDownloadURL(imageRef).then((url) => { return url; }); }; Even tho ...

Spinning the font-awesome icon on an ajax request

Below is my AJAX code: $.ajax({ type: "POST", url: "shoppingcart_service.asmx/RegisterSubscriber", data: "email=" + SubscriberEmail, // Data in form-encoded format //contentType: "application/x-www-form-urle ...

Mediawiki functionality experiencing issues within iframe display

Currently, I am working with MediaWiki built in PHP. Due to certain reasons, I have to embed this application within an iframe. All functionalities are running smoothly except for the Edit link for pages. The issue arises when I try to access the second li ...

Storing text entered into a textarea using PHP

In a PHP page, I have a textarea and I want to save its content on click of a save button. The insert queries are in another PHP page. How can I save the content without refreshing the page? My initial thought was using Ajax, but I am unsure if it is saf ...

The Angular Reactive Forms error message indicates that attempting to assign a 'string' type to an 'AbstractControl' parameter is invalid

While attempting to add a string value to a formArray using material forms, I encountered the following error message: 'Argument of type 'string' is not assignable to parameter of type 'AbstractControl'.' If I try adding a ...

establishing a minimum number of characters in a regular expression enclosed in parentheses

/^[a-z]+[0-9]*$/igm Tom //valid tom12123 //valid 12tom //invalid to12m //invalid T23 //valid T //valid but I want a minimum of two characters. /^([a-z]+[0-9]*){2,}$/igm Tom //valid tom12123 //valid 12tom //invalid to12m //should be inval ...

Utilizing regular expressions on a URI parameter in JavaScript

I implemented an ajax function that retrieves three images (PORTRAIT, SQUARE, and LANDSCAPE) from a JSON response: $.ajax({ url: link, method: 'GET', headers: { "Authorization": authToken ...

Using Typescript to iterate through an array of objects and modifying their keys using the forEach method

I have an object called 'task' in my code: const task = ref<Task>({ name: '', description: '', type: undefined, level: 'tactic', participants: undefined, stages: undefined, }); export interface Tas ...

Moving Cursor Automatically to the End Upon Rejecting Input

I have a form input where users can enter values. I need to validate the inputs to ensure they only contain numbers, dots, and commas. If the input is invalid, I want to prevent it from being stored in the input field. To achieve this, I have implemented ...