"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

Retrieve files from server using Ajax in a .NET web form application

I have a .NET web form application where I am implementing a feature to download an excel file on button click using AJAX. To achieve this, I have created a custom class: public class ImmunizationHelper { public void DownloadFile(String FileTitle, Str ...

Using Node.js to render when a task has been completed

I am currently developing a Node.js Application using Express.js. One of the challenges I face is rendering data from another site on a page using Cheerio.js. While this in itself is not an issue, I struggle with determining how to render the data once the ...

Storing Boolean values in MongoDB with Express JS: A Step-by-Step Guide

I am encountering an issue where a Boolean value that I am trying to store in Mongodb always returns false. Below is the schema of my database: const UserSchema = new Schema({ name: String, password: { type: String, required: true }, isAdmi ...

Issue with displaying jqplot in a jQuery page

Currently, I'm utilizing jqmobile pages for switching between various pages in an html5 application. One of these pages features a jqplot chart. Below is the code snippet: <div data-role="page" id="page-two" data-title="Page 2"> &l ...

Combining two arrays filled with objects to form a collection of Objects on a Map

In my JavaScript code, I'm receiving data from a WebService that looks like this: { "fire": { "totalOccurence": 2, "statsByCustomer": [ { "idCustomer": 1, "occurence": 1 }, { "idCustomer": 2, ...

Using AJAX, SQL and PHP to send data to a separate page for processing

This is the code I use to retrieve questions via ajax from a list of questions stored in a SQL database. <form id="reg-form3"> <ul class="nav nav-list primary push-bottom"> <? $db['db_host']="localhost"; ...

I need RxJs to return individual elements to the subscriber instead of an array when using http.get

I've been developing an Angular 2 app (RC5) with a NodeJS backend RESTful API integration. One specific route on the backend returns an array of 'Candidates': exports.list = function (req, res, next) { const sort = req.query.sort || null ...

Design the parent element according to the child elements

I'm currently working on a timeline project and I am facing an issue with combining different border styles for specific event times. The main challenge is to have a solid border for most of the timeline events, except for a few instances that share a ...

exploring the ins and outs of creating computed properties in TypeScript

How can I store an object with a dynamically assigned property name in an array, but unsure of how to define the array properly? class Driver { public id: string; public name: string; constructor(id , name) { this.id = id; th ...

Storing video blobs in the filesystem using Electron and Node.js

My electron application allows users to record video from their webcam using the MediaRecorder API. After hitting the "stop record" button, I am able to obtain a blob of the recorded video. I am trying to figure out how to convert this blob into a real w ...

Obtain the model value using Yii jQuery and then proceed to submit the form

Within the _form.php view, there is a presence of $model and a CActiveForm $form. I implemented JavaScript code to compare the value of $model->publication_date with the current date. If they are identical, the form will be submitted automatically. Othe ...

Alternating the tooltip icon based on the field's condition

Looking for a way to create a tooltip for an input field that involves changing icons based on certain conditions. An example scenario is the password field in a registration form. Seeking advice on the best approach to achieve this. Currently, here' ...

Service has not been properly declared

I encountered an issue with AngularJS where I am struggling to import a Service from one module to another. In the Data module, I have a Service named MenuDataService that I need to utilize in the MenuApp module. However, when attempting to do so, I receiv ...

Sending a collection of data to a Django view using jQuery's ajax function

I am currently facing a challenge in passing a list of numeric values (ids) from one webpage to another using a jQuery ajax call. Despite successfully posting and reading a single value, I am struggling with passing and reading multiple values. Below is th ...

Leveraging jQuery plugin within a React ecosystem

While utilizing semantic react, I found myself in need of a date picker. Fortunately, I stumbled upon this library: https://github.com/mdehoog/Semantic-UI-Calendar However, I am unsure how to incorporate it into my react-based project since it's not ...

Exploring the ways to access inner contents of a Div element using ajax

Looking to update the SQL database with a list of variables sent from an HTML page. Some data is being sent correctly, while others are not. The list is placed in a div divided into two parts: "h1" and another "div". The header data is being sent correctly ...

Appropriate occasion for a concealed field in the user interface grid

Currently, I am utilizing the ui grid feature. Within this feature, there is an option called hide column. I am interested in receiving an event when a user hides a column. Specifically, I would like to display an alert when a column is hidden. Is there a ...

Translation of country codes into the complete names of countries

Currently, my code is utilizing the ipinfo.io library to retrieve the user's country information successfully. This is the snippet of code I am using to fetch the data: $.get("https://ipinfo.io?token=0000000000", function(response) { console.log ...

Exploring the possibilities: Utilizing HTML5, File API, and jQuery to

I have a form displayed in a dialog and it includes a "submit" button which, when clicked, utilizes jQuery to send the form data to the server via AJAX. However, I encountered an issue where the uploaded file was always null. After researching on Google, I ...

"In a single line, add an item to an array based on a specified condition

I am trying to achieve something similar in JavaScript with a one-liner. Can this be done without using an if statement? // These versions add false to the array if condition = false let arr = await getArray(params).push(condition && itemToAdd); arr = awai ...