Creating interactive buttons on the fly in Angular

In my Angular application, I am attempting to create a button dynamically that calls the deleteRow() function and passes a username parameter upon click. Despite successfully passing the username to the controller, the generated button ends up passing undefined to the deleteRow() function. I suspect there may be an issue with how I am utilizing $compile. Have a look at the code snippet below:

validationApp.controller('usersController', function ($scope, $compile, $http, $timeout){
    $(document).on("click", ".open-confirm-dialog", function () {
        var username = $(this).data('id');
        var btnHtml = '<button class="btn btn-danger" data-title="Delete" ng-click="deleteRow(' + username + ')">DELETE</button>';
        var temp = $compile(btnHtml)($scope);
        angular.element(document.getElementById('deleteButton-dynamic')).append(temp);
    });

    $scope.deleteRow = function(username){
        alert(username); //This shows 'undefined' in the pop-up
        var request = $http({
        method: "post",
        url: "scripts/delete.php",
        data: { un: username },
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });

    request.success(function() { });
    location.reload();
};

Here is the corresponding HTML code:

<div class="row" ng-controller="usersController">
    <div class="table-responsive col-md-12" ng-show="filteredItems > 0">
    <table id="users" class="table table-bordred table-striped">
        <thead>
            <th ng-click="sort_by('username');">Username:&nbsp;<i class="glyphicon glyphicon-sort"></i></th>
            <th ng-click="sort_by('submitted_info');">Submitted Info.:&nbsp;<i class="glyphicon glyphicon-sort"></i></th>
        </thead>
        <tbody>
            <tr ng-repeat="data in filtered = (list | orderBy : predicate :reverse)">
                <td>{{data.username}}</td>
                <td>{{data.submitted_info}}</td>
                <td><a href="#confirmModal" class="open-confirm-dialog" data-toggle="modal" data-id='{{data.username}}'><span class="glyphicon glyphicon-trash"></span></a></td>
            </tr>
        </tbody>
    </table>

    </div>
        <div class="col-md-12" ng-show="filteredItems == 0">
            <div class="col-md-12">
                <h4>No customers found</h4>
            </div>
        </div>
        <div class="col-md-12" ng-show="filteredItems > 0">
        <div pagination="" page="currentPage" on-select-page="setPage(page)" boundary-links="true" total-items="filteredItems" items-per-page="entryLimit" class="pagination-small" previous-text="&laquo;" next-text="&raquo;"></div>
        </div>

        <!-- Confirm Modal -->
        <div id="confirmModal" user-id="" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="confirmModal" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
                    </div>
                <div class="modal-body">
                Are you sure you want to delete this user from the database?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>     
                <span id="deleteButton-dynamic"></span>
                <!--Working HardCoded Button
                <button class="btn btn-danger" data-title="Delete" ng-click="deleteRow('user1')">WorkingButton</button>
                -->
            </div>
        </div>
    </div>
</div>

Answer №1

When using Angular, it's important to remember that the value passed to the deleteRow function is treated as part of an expression. This means that Angular will look in the scope for a key that matches the value of the username. To avoid any errors, make sure to update the ng-click expression by enclosing the concatenated username string in quotes, like this: deleteRow(\''+ username + '\')

Answer №2

Recommendation: Implement a directive.

Here are the steps to achieve this based on the provided code snippet:

  1. Define the directive's JavaScript code:

// Begin by defining the directive controller

function dynamicButton ($scope, $http){
    $scope.deleteRow = function(){
        // The value of $scope.username is derived from the parent controller
    };
});

// Register the directive with AngularJS

validationApp.directive(dynamicButton.name, function(){
  return {
    controller: dynamicButton.name,
    restrict: 'E',
    templateUrl: 'pathtoyourhtmlpartial',
    scope: {
      username: '='
    }
  }
}
  1. Update the HTML: Call the directive from the original controller and create the new partial for the button.

  1. Activate the directive in your original controller. For instance, set $scope.buttonSwitchedOn to true. AngularJS will then automatically load and execute your directive.

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

Vue.js has mysteriously stopped functioning

My Vue.js project suddenly stopped working and I've been trying to figure out the issue for hours with no luck. Here's an overview of my HTML file which includes dependencies and a table displaying data from users. <!DOCTYPE html> <html ...

Set restrictions on the element with a fixed position

My div has a position: fixed that scrolls correctly, but I want it to stop when it reaches specific y-axis boundaries. How can I achieve this without flickering and maintaining performance? The behavior of Twitter's right panel is similar to what I&ap ...

Storing transformed values in a React Functional Component: Best Practices and Considerations

Imagine having a complex calculation function like this: function heavyCalculator(str:string):string{ //Performing heavy calculations here return result; } function SomeComponent({prop1,prop2,prop3,prop4}:Props){ useEffect(()=>{ const result ...

Incorporate the block-input feature from sanity.io into your next.js blog for enhanced functionality

Currently, I'm in the process of creating a blog using next.js with sanity.io platform. However, I am facing some difficulties when it comes to utilizing the code-input plugin. What's working: I have successfully implemented the code component b ...

Why isn't the JavaScript if statement working properly when checking the length?

Below is an if statement that I have devised: var TotalMoney=0; var Orbs=0; if (TotalMoney.length==2) { Orbs+=1; } The intention behind this code snippet is to increase the value of "Orbs" by 1 when the digit length of "TotalMoney" equals 2. However, it& ...

Enhance the appearance of the jQuery document.ready function

I'm attempting to customize the jQuery document.ready function <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript> $(function() { c ...

Guide on utilizing popup box input to amend CSS (background color)

I'm looking for some guidance on JavaScript and CSS. Is there a way to create a popup box where users can input a color (any main primary color recognized by CSS) and then have the background color of the page change accordingly in an external styles ...

Transitioning in Vue.js can be triggered by changing a value up or down

My current transition block component is set up like this: <div v-if="!surveyResultIsReady" class="vh-md-40 position-relative" > <transition name="custom-classes-transition" enter-active-class="animated slideInRight" ...

Populate my empty arrays with information retrieved from Firebase

I am currently working on creating a "single client" view for my application. Each client has a first name (prenom) and a last name (nom). However, even though my application recognizes that these values exist for each client, they do not appear on the scr ...

Retrieve the weekday dates for a specific year, month, and relative week number using Javascript or Typescript

I am in need of a custom function called getDaysOfWeekDates that can take a year, a month (ranging from 0 to 11), and the week number of each month (usually 4-5 weeks per month) as parameters, and return a list of dates containing each day of that particul ...

What is the best way to incorporate dynamic HTML content into the designated section?

I have the concept of including a text box in each dynamically created div. HTML <!DOCTYPE html> <html> <head> <title>trial </title> <meta charset="utf-8"> <meta name="viewport" cont ...

Discover the way to utilize the java enum toString() function in jQuery

In my Java Enum class called NciTaskType, I have defined two tasks: Pnd Review Woli and Osp Planning. public enum NciTaskType { PndReviewWoli, // 0 OspPlanning, // 1 ; @Override public String toString() { switch (this) ...

How to open external links in a Cordova app using AngularJS

Exploring how to use ng-bind-html in a Cordova application to launch an external link. I have successfully added the InAppBrowser pluginhttps://i.sstatic.net/Ixe8S.png Following the precise steps outlined in this guide https://gist.github.com/rewonc ...

Tips for creating an illustration in Vue.js

As I attempt to create an image using canvas, my browser throws this error at me: Uncaught TypeError: Cannot read property 'drawImage' of undefined at Image.img.onload (test.js:23) To troubleshoot, I added some console.log() messages and here ...

How can I reset a CSS position sticky element using JavaScript?

I have created a page where each section fills the entire screen and is styled using CSS position: sticky; to create a cool layered effect. Check it out here: https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark ...

Unusual Behavior of JavaScript for..in and enum

I'm facing an issue with the peculiar behavior of the for..in loop in JavaScript. Here's the structure of my HTML: <div id="quarter_circle_top_left">...</div> <div id="quarter_circle_top_right">...</div> <div id="quart ...

Displaying the structure of a MongoDB database using Express and Angular in a tabular format

I am looking to present the data from MongoDB in a table format using HTML along with Node.js, Express.js, and Angular.js. Currently, my approach is as follows: route.js app.get('/superhero', function(req, res) { superhero.superhero_list(r ...

Tips for showing ng-repeat items solely when filters are applied by the user

Is there a way to only display elements when a user uses a filter? For instance: $scope.elements = [{name : 'Pablo', age : 23}, {name : 'Franco', age : 98}]; <input type="text" ng-model="searchText" /> <div ng-repeat="elemen ...

Eliminating blank elements from arrays using JavaScript

I'm looking for some assistance in deciphering the functionality of my code. I'm trying to create a function that will take a string as input and eliminate all letters, leaving only numbers behind. The goal is to have this function return an arra ...

FlexSlider in WordPress is failing to display captions

Before pointing out any similar questions, please note that the answer from those sources does not apply to my specific code. I am trying to achieve this through a function as outlined here But I am struggling to figure out how to add captions only if th ...