Unique text: "Enhancing User Interaction: Using a custom directive to dynamically evaluate

Introduction:

A simple demonstration of HTML structure:

<td ng-repeat="col in cols">
    <div ng-bind-html="col.safeHTML"></div>
</td>

JavaScript controller code snippet:

$scope.cols = [
    {
      field       : 'logo',
      displayName : 'Logo',
      cellTemplate: '<div style="color:red">{{col}}</div>'
    },
    {
      field       : 'color',
      displayName : 'Color',
      cellTemplate: '<div style="color:green">{{col}}</div>
    }
  ];

Linking the directive with JavaScript using link function:

        for (var i = 0, j = $scope.cols.length;
               i < j;
               i++) {

            if ($scope.cols[i].hasOwnProperty('cellTemplate')) {
              $scope.cols[i].safeHTML = $sce.trustAsHtml($scope.cols[i].cellTemplate);
            }
          }

Although the HTML is being properly escaped, the dynamic bindings like {{some_var}} are not getting processed. How can we ensure Angular evaluates the bindings within the safe HTML content? I've attempted to utilize different binding methods such as ngBindTemplate without success :(

Answer №1

If you are looking to dynamically compile Angular components and manually add them to the DOM, it is recommended to utilize the $compile service.

By incorporating some custom directive work, achieving this functionality can be quite straightforward.

function dynamicCompile($compile) {

  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      // Monitor changes in expression
      scope.$watch(attrs.dynamicCompile, function(newVal) {

        // Compile generates a linking function
        // that can be used with any scope
        var link = $compile(newVal);

        // Executing the linking function
        // creates a new element
        var newElem = link(scope);

        // We can then append this new element to our existing DOM element
        elem.append(newElem);
      });
    }
  };

}


function columnsCtrl() {
  this.columns = [{
    name: "Heading with H1 tag",
    template: "<h1>{{column.name}}</h1>"
  }, {
    name: "Text in red span",
    template: "<span style=\"color:red\">{{column.name}}</span>"
  }];
}

angular.module('sample', [])
  .directive('dynamicCompile', dynamicCompile)
  .controller('columnsController', columnsCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.4/angular.min.js"></script>
<div ng-app="sample">

  <ul ng-controller="columnsController as ctrl">
    <li ng-repeat="column in ctrl.columns">
      <!-- The "dynamic-compile" attribute is our custom directive -->
      <div dynamic-compile="column.template"></div>
    </li>
  </ul>

</div>

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

Having trouble with the ngSwipe feature?

I am currently developing a touch screen application for my client using AngularJS. In order to implement swipe functionality, I am utilizing ngTouch along with the directives ng-swipe-left and ng-swipe-right. I have also created functions that should be t ...

"Safari (iOS) is experiencing a functionality issue where Alert() is working, but console.log() is

Just a heads up before you dive in: I've encountered an issue with Safari related to Chrome, but it seems to work fine on other browsers. So, it could be more OS-specific rather than a general problem. I recently ran into a frustrating situation whil ...

Storing information within a Express application using Postgres

Recently, I've been delving into the world of Express and experimenting with a program that allows users to create events and invite others. While I know about using join tables to retrieve data, I'm curious if there's a way to organize the ...

Include a personalized header when making an HTTP GET request with AngularJS

This is my angularjs request. var req = { method: 'GET', url: 'http://localhost:8080/test', headers: { "x-auth-token" : user.token } } ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

The userscript is designed to function exclusively on pages originating from the backend, rather than on the frontend in a single-page application

I have a userscript that I use with Greasemonkey/Tampermonkey. It's set to run on facebook.com, where some pages are served from the backend during bootstrapping and others are loaded on the fly in the front-end using HRO, similar to how a Single Pag ...

Is it possible to maintain a fixed footer while utilizing async/ajax functions?

Looking for a reliable solution to have a fixed footer that adjusts based on the page content? I've tested multiple samples, but they all fall short when it comes to incorporating AJAX elements. Is there a fixed footer out there that truly works seaml ...

React - Paths of images converting to relative when directly accessed via the address bar

Whenever I click on a route link, everything works perfectly. The images have the correct path in the DOM and load successfully. However, if I manually type the URL into the address bar with the route suffix included, like example.com/services, the image ...

Eliminating duplicate data submissions with jQuery Ajax

Encountering an issue with my jQuery AJAX submission process. JavaScript: $('#myform').submit(function () { if (validateEvenInputs()) { $('#btnevent').attr('disabled', 'disabled'); function ...

Can you please guide me on how to effectively configure a personalized time zone using MUI date picker combined with dayjs?

In my application, the user's time zone is supplied by the server instead of being determined by the browser's settings. When I receive a Unix timestamp from the server and pass it to the date picker, the displayed date is incorrect because the ...

The Gatsby node encounters an error while trying to create a new page

I am currently working on creating sub-pages for a projects category in Gatsby. The parent page for each project is generating correctly, but the sub-pages are not behaving as expected. Each project has the potential to have zero or multiple sub-pages, an ...

Determine the exact scroll position needed to reveal the element when scrolling in reverse

I'm looking for a way to make my div disappear when I scroll down and reappear immediately when I start scrolling back up. Currently, it only works when I reach a certain position instead of taking effect right away. I need assistance in calculating t ...

"Exploring the process of utilizing AngularJS to open a .docx file in a new template

When attempting to open a .jpeg or .pdf file in a new template using an iframe, it was successful. However, the same approach failed when trying to open a .docx file. How can this issue be resolved? Angularjs code: $scope.openTemplate = function ($fpath ...

What is the best way to send a JSON response from a Symfony2 controller?

I am utilizing jQuery to modify my form, which is created using Symfony. The form is displayed within a jQuery dialog and then submitted. Data is successfully stored in the database. However, I am unsure if I need to send some JSON back to jQuery. I am ...

Swap out the image for a div element if the image is not found

Is there a way to accurately display an image if it's available, and use a div as a replacement if the image is not present? // How can I determine `imageExists` without encountering cross-origin issues? (imageExists) ? (<img class="avatar-img" sr ...

Tips for executing an asynchronous fetch prior to the first rendering

Currently, I am working with the Wordpress API using Next.js on the front end. My goal is to fetch my navigation/menu data and have it pre-rendered. However, my attempts have only resulted in an empty <nav> </nav> element being rendered when I ...

How much will it set me back for '`$(this)`?

Many individuals in this community frequently recommend caching the jQuery object generated from a DOM element, as illustrated by the following code snippet: $('#container input').each(function() { $(this).addClass('fooClass'); ...

Manipulate state in parent component from child component using onClick function with React hooks

Hello, I am facing a challenge trying to store data from a modal (child function) within the main (parent) function. Depending on which button is clicked, the modal loads specific HTML content (all buttons perform the same action). export default function ...

Is there a way to deactivate the toggle button in my code?

<label class="switch switch-yes-no" id="disable_'+id+'" style="margin: 0;font-weight: bold;"> <input class="switch-input" type="checkbox" id="disable_'+id+'" /> <span class="switch-label" data-on="Enabled" data-off="Disab ...

Search for elements with a specific substring in their class names using the querySelectorAll() method

I'm working with a custom component in app.js return ( {cards.map((index) => { return <Card key={index} /> ) Within the Card component, I assigned a specific className return ( <ListItem id="root" className="find-card"&g ...