Invoke the controller function programmatically through dynamically generated HTML

In my controller, there is a function named $scope.removePoster. Within the same controller, there is a table creation function that calls $scope.removePoster like so:

for(var i=0; i < 6 && postersNum >= 0; i++){
  ...
  table += '<td align="center">';
  table += '<img width="150" height="175" src="../js/librerias/carousel/images/'+$scope.posters[indexPosters]['image']+'"><br>';
  table += '<button type="button" class="btn btn-danger" ng-click="removePoster('+$scope.posters[indexPosters]['id']+')">Delete</button>';
  table += '</td>';
  ...

However, when I include this table in my HTML, the button fails to trigger the function.

Answer №1

It appears that you are implementing something similar to the following:

<!-- HTML -->
<table>
    <tr ng-repeat="poster in posters | limitTo: 6">
        <td align="center">
            Poster {{poster.id}}
            <img width="15" height="18" 
                 ng-src="../js/librerias/carousel/images/{{poster.image}}" />
            <button type="button" class="btn btn-danger" 
                    ng-click="removePoster(poster.id)">
                Delete
            </button>
        </td>
    </tr>
</table>

// Controller:
$scope.posters = [];
$scope.getPosters = function (url) {
    $http.post(url, {'method' : 1}).success(function (data, status) {
        $scope.posters = data;
    });  
};
$scope.removePoster = function (id) {
    $scope.posters.some(function (poster, idx) {
        if (poster.id === id) {
            $scope.posters.splice(idx, 1);
            return true;
        }
    });
};

Also, take a look at this quick demo.


Here are some key points:

  1. Using ngRepeat with the <tr> element allows Angular to generate the necessary tr elements based on the content of posters (with a limit set to 6).

  2. The limitTo filter by Angular restricts the posters array to display only the first 6 items in the ngRepeat. Any changes in the posters array will automatically update the DOM accordingly.


IMPORTANT

While this implementation provides a basic understanding of dynamically creating tables in Angular, it may not be the most optimal approach for all scenarios. In a real-world application, consider using a service to fetch data from the server and injecting it into the controller for better organization and data handling.

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

Trying to assign a value to the property 'male' of an undefined object - error encountered while setting object value from an array

Why is it that when I add one more testObject, the code doesn't work anymore? The line of code where only one testObject is used works fine (testObject[Object.values(testObject)[0]]=5), but adding another testObject causes issues. const testObject ...

Tips on transferring HTTP data from a service to a controller in AngularJS

var locationListCtrl=function($scope, loc8rData){ $scope.message = "Looking for nearby places"; loc8rData .success(function(data){$scope.message = data.length > 0 ? "" : "No locations Found"; ...

Is the AJAX $.ajax() function and setInterval() method activated only when a user is actively viewing the page?

The following code was created by me in order to refresh or reload the content within the div id='bitcoin_blocks_table', which only occurs when a user is actively on the website. I noticed that if no one is on the site and I return after 2 hours ...

The act of initiating a click on a radio button involves evaluating conditions prior to toggling

Apologies for the slightly ambiguous title, let me provide a clearer explanation. I have created a codepen to demonstrate an issue that I am facing. You can view it here. In my codepen, I have two toggle buttons labeled "Male" and "Female" for simplicity. ...

Modal window closed - back to the top of the page

I am struggling with a simple modal popup window that does not maintain the scroll position when closed, instead returning you to the top of the page. I am looking for a way to keep it at the same scroll position without much knowledge of Javascript. You ...

"Exploring the features of next-auth server-side implementation in the latest version of Next.js,

Is it possible to utilize next-auth in a Next.js 14 application router to access user sessions and display page responses using SSR? If so, what steps need to be taken? ...

How to effectively pass custom props or data to the Link component in Next JS

As I dive into Next JS, I've hit my first roadblock. Currently, I am working on a page that showcases various podcast episodes with preview cards on the homepage. The card component code looks like this: import React from 'react'; import Li ...

Receiving a "Maximum call exceeded" error when using Vue.js router guards for the beforeEach hook

As I work on my Firebase-VueJS app, I am implementing basic security rules with router guards. In my main.js file, I have added the following code to handle permissions based on the user's authentication status. However, I encounter an error 'vue ...

Using jQuery cookies to dynamically change the body id during page loading

Is it possible to dynamically change the body ID during page load? I recently created an application that successfully changes the body ID. Now, I'm interested in detecting the body ID that I have already selected during page loading. Below is the c ...

Do I have to divide the small functions in my Node.js controller into smaller ones?

When signing up users in my controller, do I need to break up the sign-up steps into individual asynchronous calls or is one big asynchronous call sufficient? Each step relies on the previous one: Validate user Create user Create group Add user to group ...

Utilizing $stateParams within a personalized ui-router configuration attribute

Attempting to retrieve data from $stateParams within a custom ui-router state configuration property results in an empty object being logged. This outcome is anticipated given that I am straying from the standard ui-router configuration. Despite this devi ...

Infinite scrolling with Jquery: Loading dynamic content seamlessly from external websites

Hey there! I recently started using this cool jQuery plugin called jquery-endless-scroll. Here's a snippet of my code: $(function() { $('#list').endlessScroll({ pagesToKeep: 10, fireOnce: false, insertBefore: "#list div:first ...

What is the best way to reveal the square's id value upon hovering over it exclusively?

In this assignment, I am refraining from using HTML and focusing on JavaScript to create functionality. Here's my progress so far: document.addEventListener("DOMContentLoaded", function () { let button = document.createElement('button' ...

Is it true that AngularJS is unable to update data attributes?

I'm working with an input element that utilizes the type-ahead plugin from bootstrap. My goal is to dynamically set the data-source attribute as the user types, creating a real-time search effect. <input id="test" data-provide="typeahead" data-sou ...

Exploring the concept of upserting records using the MongoDB $

I am working with two collections in my database: Regions and Registrations. var RegionSchema = new Mongoose.Schema({ name: {type: String}, registrations: [{type: Mongoose.Schema.Types.ObjectId, ref: 'registrations'}], ... }); The Registr ...

What does the JS Array Filter function return?

Is it necessary to include a return statement in the filter function when NOT using ES6 arrow syntax? Could the two separate filter functions be combined into one for efficiency? cars.filter(function(car, index) { return car[0].setAttribute("data-ori ...

Adjust the sizes of the points according to the level of zoom

I've been working on creating a dynamic map in d3.js that displays US Science funding agencies as points, with their sizes scaling based on zoom level. I referred to this starter kit for guidance. While there are other solutions out there, they often ...

The input field does not contain the chosen date

Utilizing the react-dates library from Airbnb for date selection has been a bit challenging in conjunction with redux form. Upon clicking the select date button, the calendar interface appears. However, upon choosing a date, the input box remains empty ins ...

Utilize AJAX or another advanced technology to refine a pre-existing list

I am trying to implement a searchable list of buttons on my website, but I haven't been able to find a solution that fits exactly what I have in mind. Currently, I have a list of buttons coded as inputs and I want to add a search field that will filte ...

Is using canvas the best option for creating simple image animations with JavaScript?

I am currently working on a basic animation project using JavaScript. This animation involves switching between 13 different images per second to create movement. I have created two simple methods for implementing this animation. The first method involves ...