Implementing HTML with onclick functionality in an AngularJS view

I am currently facing a challenge in rendering HTML in my view and integrating a function call within this HTML. I'm struggling to find a way to accomplish this task. Below is the snippet of my JavaScript code:

        angular.forEach($scope.patients, function (patient) {
         tableRow = tableRow + [
             '<div data-ng-click="popup("+patient+")">',
                 '<div class="name-container">+patient.name+</div>',

             '</div>'].join('');
    });
    $scope.renderHTML =$sce.trustAsHtml(tableRow);

    $scope.popup = function(patient) {
    ...

};

Snippet of HTML code:

  <div data-ng-bind-html="renderHTML">
             </div>

My question is: Can the patient object be passed to the popup() function using this approach?

Answer №1

When working with HTML and JavaScript, $eval can be useful for evaluating different angular expressions.

<div data-ng-bind-html="$eval(renderHTML)">
             </div>

If you are using JS, the following code snippet may help:

angular.forEach($scope.patients, function (patient) {
         tableRow = tableRow + [
             '<div data-ng-click="popup("'+patient+'")">',
                 '<div class="name-container">'+patient.name+'</div>',

             '</div>'].join('');
    });
    $scope.renderHTML =$sce.trustAsHtml(tableRow);

    $scope.popup = function(patient) {
    ...

};

There is a suggestion to avoid passing patient object directly in the popup function. Use JSON.stringify if needed. For more information, check out this link: How to make ng-bind-html compile angularjs code

Suggestion:

You may want to consider using the ng-repeat directive instead of angular.forEach. Here's an example using ng-repeat:

 <div ng-repeat="patient in patients">
        <div data-ng-click=popup(patient)>
           <div class="name-container">patient.name</div>
           </div>
        </div>
    </div>

MODIFIED:

Consider trying this modification:

angular.forEach($scope.patients, function(value,key){
         tableRow = tableRow + [
             '<div data-ng-click="popup("'+patients[key]+'")">',
                 '<div class="name-container">'+patients[key].name+'</div>',

             '</div>'].join('');
    });
    $scope.renderHTML =$sce.trustAsHtml(tableRow);

    $scope.popup = function(patient) {
    ...

};

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

React component will automatically rerender if the cache is disabled in the Chrome browser

In my React application, I am utilizing 'react-image-pan-zoom-rotate' to display images. Visit the GitHub repository here The image I am displaying is sourced from an external service and passed to both libraries for rendering. Lately, I have ...

Encountering a DOM exception with React 16.6 due to lazy loading/Susp

I am currently working on implementing dynamic import in my React application. Most of the React examples I have seen involve rendering the application to a specific tag and replacing its content, like this: ReactDOM.render(<App />, document.getEle ...

Fine-tuning CSS layout based on perspective alteration

I am working with the following code: function exportTableToExcel(tableID, filename = ''){ var downloadLink; var dataType = 'application/vnd.ms-excel'; var tableSelect = document.getElementById(tableID); var tableHT ...

When creating utility classes, is it beneficial to offer a non-mutable API to facilitate their integration with frameworks such as React?

Currently, I am working on enhancing the functionality of my DateWithoutTime class. As part of this process, private fields within the class need to be updated by public methods. this.state.dateWithoutTimeInstance.shiftBySpecificDaysCount({ daysCount: 5, ...

Tips for resolving a flickering issue that occurs when switching to an input field with our default value / placeholder plugin

In the realm of web development, numerous plugins cater to the implementation of HTML5's placeholder attribute in older browsers. The plugin we have opted for can be found here. Unlike some other alternatives, this particular plugin, with a few modif ...

The behavior of Elementor lightbox buttons upon being clicked

When using Android, I've noticed that the lightbox briefly displays a semitransparent cyan bar on the left and right buttons when they are pressed. Is there a way to control or prevent this behavior? Any suggestions would be appreciated! Thanks in adv ...

There was an unexpected error: Unable to access the 'bool' property of an undefined object

{ "name": "unique-react", "version": "2.0.1", "private": true, "scripts": { "start": "webpack-dev-server --hot --port 3002 --open --inline", "build": "cross-env NODE_ENV=production rimraf dist && webpack", "package": "webpack -p ...

AngularJS Service failing to appear on screen

I am trying to access my Github information using Github's API. I can see the correct information when I log my http request, but for some reason it is not showing up on the page. There are no errors being thrown, but the requested data is not display ...

Leveraging the Google Feed API using jQuery's AJAX functionality

Currently, I am attempting to utilize Google's Feed API in order to load an RSS feed that returns a JSON string. (For more information, please refer to: https://developers.google.com/feed/). Despite this, my approach involves using jQuery's AJ ...

What is the best way to selectively remove and then later reinsert two items from an array in

I am facing a scenario where I have two buttons and an array to work with. The buttons are labeled "OR" and "AND", and the array consists of 7 items in a Dropdown list. When the user clicks on the "OR" button, it should remove 2 items from the array. Co ...

Retrieve checkbox selected value using pug and node.js

How can I retrieve the value of a checked checkbox in order to redirect to (href="/player/edit/:id") or (href="/player/delete/: id"), and obtain the player id for editing or deleting? I have omitted other code details such as app.js which includes the ser ...

Tips for extracting title and image from someone else's blog posts to share on your own website

Currently, I am in the process of creating a website where I can showcase my personally curated content. I have been struggling to figure out how to seamlessly integrate this content into my site without relying on an API. My initial idea was to manually ...

Angular 2 Issue: Unable to connect to 'routerlink' because it is not recognized as a valid property of 'a' tag

As a newcomer to Angular 2, I am attempting to create a sample application based on a Pluralsight tutorial. However, I encountered the mentioned error when trying to set up Routes. I am struggling to identify the cause of this error. Any assistance would ...

What is the best way to retrieve the value of a nested function in JavaScript?

I am currently working on a project that involves a function. function findParentID(parentName) { Category.findOne({ categoryName: parentName }, function (err, foundParent) { var parentID = foundParent.categoryID;    return parentID;<br> } ...

Rails inspired tag selection tool akin to Stack Overflow

In my Rails application, I am looking to implement a tagging system for models. I want to create a tag selection feature similar to Stack Overflow where I can type in a tag like 'rails' and a drop-down list of options containing that tag will app ...

JQuery, Draggable delete

I created a shopping cart with drag-and-drop functionality for nodes. http://jsfiddle.net/dkonline/Tw46Y/ Currently, once an item is dropped into the bucket (slot), it cannot be removed. I'm looking to add that feature where items can be removed from ...

Display a visual progress indicator during audio recording

I am currently using the MediaRecorder functionality to capture audio and I would like to display a progress bar showing the recording process. Here is the code snippet from my recorder template: <p id="countdowntimer">Current Status: Beginning in& ...

Tips on increasing the height of an element that is overflowing

When populating my timeline component with dynamically mapped data from an array, I encountered an issue where if I added more data causing the maximum height to be reached, the overflow-y element didn't display all content. Despite trying various sol ...

What could be causing Mathjax to generate multiple copies?

I have integrated MathJax into my application to render MathML. The code snippet below is used to ensure that the MathML is typeset properly: $rootScope.$watch(function() { MathJax.Hub.Queue(["Typeset", MathJax.Hub]); return true; }); However, I ...

Modify the behavior of the Android back button when a Popup is displayed in Ionic

I'm attempting to accomplish the following: Scenario 1 User presses the back button. A popup appears asking if the user wants to exit * User presses the back button. The app exits * and Scenario 2 User presses the back button. A popup ...