Insert an HTML element prior to the content using the ng-bind directive

I am working with a table that is generated by an ng-repeat loop and connected to a model using ng-bind. In the first column, I want to dynamically add an HTML element based on a specific condition. How can I accomplish this?

<!doctype html>
<html ng-app="plunker">

<head>
<script data-require="angular.js@*" data-semver="1.2.0" src="http://code.angularjs.org/1.2.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<body>
<div ng:controller="MainCtrl">

<table border="1">
  <thead style="font-weight: bold;">
    <tr>
      <th class="text-right" ng-repeat="column in columnsTest" ng-if="column.checked" ng-bind="column.id"></th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in rows">
      <td ng-repeat="column in columnsTest" ng-if="column.checked" ng-bind="formatValue(row[column.id], column.id == 'Value1')"></td>
    </tr>
  </tbody>
</table>
</div>




<script>
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $filter) {



  $scope.formatValue = function(value, addIcon) {

    if (addIcon) {
      var htmlElement = '<span>This is a SPAN</span>'

      value = htmlElement + value;
    }

    return value;
  }


  $scope.columnsTest = [{
    id: 'Value1',
    checked: true
  }, {
    id: 'Value2',
    checked: true
  }, {
    id: 'Value3',
    checked: true
  }];


  $scope.rows = [{
    id: 1,
    "Value1": 911,
    "Value2": 20,
    "Value3": 20
  }, {
    id: 2,
    "Value1": 200,
    "Value2": 20,
    "Value3": 20
  }];



});

I want to ensure that my HTML element appears before the value in the first column. I attempted to use $scope, but the span still displays as text. How can I correct this?

View the code on Plunker

Answer №1

Keep the controller separate from HTML knowledge. Use the ngIf directive to selectively include a span:

<tr ng-repeat="row in rows">
    <td ng-repeat="column in columnsTest" ng-if="column.checked">
        <span ng-if="column.id == 'Value1'">ICON</span>
        {{ row[column.id] }}
    </td>
</tr>

Check out the live demo: http://plnkr.co/edit/oUtzD2lQoF29PyOgs2k4?p=info

Answer №2

To properly display HTML content in AngularJS, you will need to utilize both ng-sanitize and ng-bind-html.

The ng-bind-html directive will securely insert the resulting HTML into the designated element. By default, the HTML content is sanitized using the $sanitize service.

This process ensures that the HTML content is inserted safely into the element.

var app = angular.module('plunker', ['ngSanitize']);

$scope.formatValue = function(value, addIcon) {

    if (addIcon) {
      var htmlElement = '<span>This is a SPAN</span>'

      value = htmlElement + value;
    }

    // Wrap value with a span to comply with `ng-bind-html` requirements for root HTML.
    return "<span>" + value + "</span>";
  }

For an example, refer to the updated PLUNKER.

Answer №3

To implement sanitization in Angular, it is recommended to use ngSanitize along with ngBindHTML directive.

 <script data-require="angular.js@*" data-semver="1.2.0" src="https://code.angularjs.org/1.2.0/angular-sanitize.js"></script>
...
var app = angular.module('plunker', ['ngSanitize']);
...
<td ng-repeat="column in columnsTest" ng-if="column.checked" ng-bind-html="formatValue(row[column.id], column.id == 'Value1')"></td>

Access the Plunker example here

Answer №4

To properly bind an HTML template, it is recommended to utilize the $sce service in conjunction with the ngBindHtml directive.

For reference, check out this Revised Plunker.

Answer №5

When utilizing ng-repeat, you have the option to display a span based on the '$first' boolean using ng-if.

<tr ng-repeat="row in rows">
      <td ng-repeat="column in columnsTest" ng-if="column.checked">
        <span ng-if="$first">This is a SPAN</span>
        {{row[column.id]}}
      </td>
    </tr>

update: Opt for ng-if to enhance the rendering performance when dealing with extensive lists

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

Combining Objects in Three.js: Merge All Objects into a Single Entity

I am new to the world of three.js and recently I tried my hand at creating a custom shape using multiple objects. However, I encountered an issue where everything seemed fine when I added each object individually to the scene. https://i.sstatic.net/MWLYS. ...

Utilizing JavaScript to handle the value from a selected form

My form is quite simple: <form id="signup"> <div class="form-group"> <input type="text" name="email" placeholder="Email" id="email" required> </div> <div class="form-group"> <input type= ...

Executing JavaScript in a web browser using Delphi

Similar Question: How to trigger the OnChange event of a "Select" element in Delphi WebBrowser? Hey there, I have a TWebBrowser in Delphi that loads a webpage containing a form with a dropdown menu. I am able to select an item from the dropdown, but ...

When using React.js with Leaflet, ensure that the useEffect hook is only run on Mount when in the

I have encountered an issue where I need to ensure that the useEffect Hook in React runs only once. This is mainly because I am initializing a leaflet.js map that should not be initialized more than once. However, anytime I make changes to the component&a ...

What is the best way to retrieve both a response JSON and headers using Got?

Currently, I am utilizing Got for sending requests to a Strapi API from Node.js. The code snippet demonstrates how I achieve this: res.setHeader('Content-Type', 'application/json') try { const request = req.query.request const decod ...

I am looking to halt the AJAX requests within an asynchronous function after reaching a limit of 10 requests

I've been working on an async function that sends AJAX requests based on the previous response. The function is functioning properly, but it's sending multiple requests in quick succession. I need to implement a 5-second interval between each req ...

Attributes required are not functional on mobile devices

Good day! I have encountered an issue with the required attribute on a form on my website. It seems to be working perfectly on my browser, but not on mobile devices. Has anyone else experienced difficulties with jQuery, JavaScript, or Node packages? <f ...

Emberjs promises are enhanced with a filtering feature

My goal is to develop a search functionality using a JSON API. After following tutorials and successfully implementing it with provided examples: export default Ember.ArrayController.extend({ searchText: null, searchResults: function(){ ...

How can I execute a synchronous MongoDB query in Node.js properly?

When utilizing the Node.JS driver for MongoDB, I am interested in executing a synchronous query. Here is an example of what I am aiming to achieve: function retrieveSomething() { var database = new mongo.Db("mydatabase", server, {}); database.ope ...

The .keypress() function isn't behaving as expected

I've encountered a coding dilemma. Below is the code in question: $(document).ready(function () { var selectedDay = '#selected_day'; $(function () { $("#date").datepicker({ dateFormat: "DD, d M yy", a ...

Using Jquery and CSS to display or conceal table elements depending on viewport width

I am seeking advice for my issue. Here is the code snippet on JSFiddle. I have a list of models and corresponding values that vary across different categories. I have created a simple table to display this data. However, I need to alter the table structur ...

When using express and passport-local, the function `req.isAuthenticated()` will typically return a

I'm seeking some insight into my current situation. I've noticed that whenever I call req.isAuthenticated() in an app.router endpoint, running on port 3001 via the fetch API, it always returns false. It seems like the connect.sid is not being pro ...

Generate a JSON array containing objects consisting of a combination of string and boolean values

My goal is to generate a list containing objects with names and boolean values by utilizing AJAX. This process is initiated in the following manner: $('.si-accordion').click(function () { $(this).siblings('.accordion_tab&apo ...

What is the best way to incorporate an npm module in a django-admin widget without the need to install node?

Background I am working on a Django app and need to create an admin widget. The widget will display text in a unique terminal-style format to show forwarded logs from an analytics process managed by Django (using the django-twined extension). To achieve ...

A guide to retrieving nested values from a JSON object using JavaScript

Having trouble accessing specific values from a heavily nested JSON content returned by a URL? You're not alone! Many tutorials only cover simple nesting examples. Take a look at the code snippet I've been working on: $(document).ready(function ...

Maintaining the initial value of a textbox in jQuery across various focusin events

Struggling to accurately explain the process, so feel free to check out this helpful fiddle. In my form, there are several text input fields and a single submit button. The submit button becomes enabled once any of the form fields have been altered. If a ...

Having difficulties persisting information from freshly generated input fields with the "Add" button to the database

Currently, the issue lies with the database only accepting data from the first input field in PHP. <form class = "spendings" method ="POST" action="InsertToDatabase.php"> <div id="numbering">ITEM 1: </div> <div class="entry"> ...

An issue has been detected in the constants.json file located in the constants-browserify

I organized my folders into client-side and server-side categories, but I failed to work from a parent folder perspective. Now, as I attempt to deploy to Heroku, I realize that I need one main folder for the deployment process. To address this issue, I dec ...

Warning message regarding unhandled promise rejection in NestJS websockets

I've encountered a puzzling issue while attempting to integrate an 'events' module into my application to utilize websockets. Upon adding the module, an unexpected error surfaced: (node:59905) UnhandledPromiseRejectionWarning: Unhandled pro ...

Accessing iframe's HTML using a server-side solution by circumventing the Cross-Domain Policy

Our current challenge involves accessing dynamically generated HTML elements using JavaScript, particularly when trying to extract image URLs from these elements. When the HTML elements are generated solely through JavaScript, extracting the URL is straigh ...