Employing ng-click within a displayed column of Datatable

Currently, I am utilizing a plain Datatable in AngularJS without any Angular-Datatable libraries. Everything appears to be working well except for one issue.

Here is the datatable code snippet:

$scope.siInfoTable = $('#siInfoTable').DataTable({
            'columns': [
                {
                    "render": function (data, type, row, meta) {
                        data =  '<button class="btn btn-primary btn-sm" ng-click="test()">TEST</button>';
                        return data;
                    }
                }]
        });

This code is executed within a $scope.load method and is loaded before the page finishes rendering. However, when a user clicks on the button generated in the datatable, it does not seem to recognize the ng-click directive.

Is there a solution to this issue?

Answer №1

If you want to avoid issues, it is recommended to utilize the angular-datables angular library.

  1. Any changes in your controller or directive may not be reflected in the output HTML.
  2. You might encounter repeated errors in your application.

To simplify the process and address any problems you are encountering, consider implementing angular data tables.

Referenced from Angular Datatables Documentation


    angular.module('datatablesSampleApp', ['datatables', 'datatables.buttons']).
    controller('sampleCtrl', function($scope, DTOptionsBuilder) {
        $scope.dtOptions = DTOptionsBuilder.newOptions()
          .withPaginationType('full_numbers') 
          .withDisplayLength(2)
          .withOption('order', [1, 'desc']).withButtons([{
        text: '<button class="btn">Some button</button>',
        key: '1',
        action: function(e, dt, node, config) {
          alert('Button activated');
        }
      }]);
    });
<!DOCTYPE html>
<html>

<head> 
    <link rel="stylesheet" href="//cdn.datatables.net/1.10.1/css/jquery.dataTables.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.9/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.6.2/angular-datatables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.6.2/plugins/buttons/angular-datatables.buttons.min.js"></script>
    <script src="script.js"></script>
</head>

<body ng-app="datatablesSampleApp">
    <div ng-controller="sampleCtrl">
        <table datatable dt-options="dtOptions">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>First name</th>
                    <th>Last name</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>Foo</td>
                    <td>Bar</td>
                </tr>
                <tr>
                    <td>123</td>
                    <td>Someone</td>
                    <td>Youknow</td>
                </tr>
                <tr>
                    <td>987</td>
                    <td>Iamout</td>
                    <td>Ofinspiration</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>

</html>

Answer №2

Make sure to compile your HTML first before assigning it to data by injecting $compile into your controller.

app.controller('mycontroller', ['$compile', ..., function($compile, ...)

Afterwards, you can proceed to compile your HTML like this:

data =  $compile('<button class="btn btn-primary btn-sm" ng-click="test()">TEST</button>')($scope);

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

The array element is not being shown in the id "main" when using a for loop with the onchange function

I've been using document.write to display specific content, but it seems to be removing other elements from the page. Is there a way for me to display this loop inside the element with id="main" without losing any content? When I attempt to use docume ...

Utilizing Jquery's each() method to retrieve the exact position of a specific class element

Is there a way to determine the position of the "owl-item active" element? The current position is 2 out of 3 total photos. <div style="transform: translate3d(-825px, 0px, 0px); transition: all 0.25s ease 0s; width: 48675px;" class="owl-stage"> ...

Difficulty in retrieving attribute information from an image - JQuery

I have been attempting to extract the attribute from images that I have obtained from a collection of ul-based image galleries using the clone function. Here is the Ul Tag I am trying to clone: <ul class="bannerscollection_zoominout_list"> ...

What is the best method for transferring data from a TextBox to a GridView, ensuring that multiple rows are accurately showcased within the GridView?

I have successfully used the code provided below to display data from a TextBox to a GridView without saving the data to the database. The current functionality allows me to enter Name and City in the TextBoxes, click on the Button, and see those values di ...

In Firefox, there is a peculiar issue where one of the text boxes in an HTML form does not display

In my HTML form, users can input their first name, last name, and phone number to create an account ID. The textboxes for first name, last name, and account ID work smoothly on all browsers except Firefox. Surprisingly, the phone number textbox doesn' ...

Is it possible to extract the value displayed on a Typography component in Material UI and store it in a state variable?

I'm currently facing an issue with mapping a data array onto material-ui Typography elements. Here's the code snippet: { array.map((item, id)=> <Typography key={id} value={item.name} />) } While this code successfully displays the val ...

Use of ng-if in combination with recursive directives does unexpected behavior

I have a situation where I am using two recursive directives inside ui-bootstrap tabs. In order to optimize performance, I want the directive to only load when its corresponding tab is active. To achieve this, I am using ng-if on the directive like this: & ...

Unleashing the Power of Conditional HTML Attribute Insertion

What is the best way to add a conditional attribute in AngularJS? For instance, I am looking to only apply the multiple attribute to a <select> element if a certain binding in my component is set to true. If this binding is not present, then the mul ...

Using jQuery Validator Plugin to verify the existence of an email address

I've integrated the jQuery Validator Plugin into my newsletter form registration for validation purposes. Utilizing the remote validate method, I'm able to verify if an email address already exists in the database. The validation method is funct ...

Using jQuery to switch between displaying full text and truncated text

How can I toggle the hidden text that appears after using the .slice function to remove the first 100 characters? This is the code snippet I am currently working with: .html <div class="col-sm-12"> <p class="pdp-product-description">Th ...

What are some effective troubleshooting methods for resolving issues with chrome.storage.sync?

My Chrome extension is a simple tool that utilizes the chrome.storage API to keep track of tasks in a organized list. Whenever there is an update to the task list, the array is saved to chrome.storage.sync. I have both of my laptops configured with the Ch ...

Implementing CSS styles according to user preferences. Switching between dark mode and light mode based on subscription

Is there a way to dynamically change CSS property values based on user interaction, such as toggling between dark mode and light mode? I am currently exploring the option of setting up a subscription to track these changes, but I want to know how I can act ...

``How can I easily navigate to the top of the page when changing routes in React Router DOM v6?

What is the best way to scroll to the top when a route changes in react router dom v6? In the past, I used a solution from this StackOverflow post to make my page automatically scroll to the top every time a route changed with react-router-dom v5. However ...

Cypress - A Guide to Efficiently Waiting for the Outcome of a Javascript Function Import

I am interested in creating a Javascript library to act as a wrapper for 3rd party APIs. I have decided to write the API wrapper as a standalone file rather than using Cypress Custom functions, so that I can share the library with teams who are not using C ...

How can I modify the dot colors on a graph using chart.js?

Need assistance with changing the color of graph data points https://i.sstatic.net/QGJBv.png Here is my JavaScript code snippet I have successfully created a graph using chart.js. However, I now want to differentiate data points by displaying different c ...

Trouble with jQuery autocomplete function in Firefox

I've implemented multiple jQuery autocomplete searches similar to this one. While they function properly in Safari, Chrome, and Opera, I'm encountering issues with Firefox. Could it be due to deprecated code usage? The jQuery UI example seems si ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

Can you explain the technical distinctions between Express, HTTP, and Connect?

const express = require("express") , app = express() , http = require("http").createServer(app) As I observe, these dependencies are commonly used. As far as I understand it, http serves front-end HTML, while express manages server-side Node.js logic. ...

User interface for creating a platform resembling Product Hunt or Reddit

I am currently developing a web application similar to Product Hunt. The back-end API is up and running smoothly, and I have successfully implemented AngularJS for the front-end. However, I lack experience in designing the look and feel of the site. Shou ...

How to Send jQuery ajax Requests with Multiple Buttons in a PHP Form

My current issue is as follows: <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> </head> <body> <form id="roomform" action="room.php" method="POST"> <b ...