Assessing string expressions within an object provided to an Angular directive

How can I evaluate string expressions in an object passed to a directive? I've reviewed various solutions but couldn't make it work as expected:

Compiling dynamic HTML strings from database

Dynamically add directive in AngularJS

How to get evaluated attributes inside a custom directive

Here is the main code snippet:

http://plnkr.co/edit/b2FblYElVGnzZRri34e0?p=preview

I'm specifically focusing on evaluating the {{units}} within the reportData object. I attempted using the $compile service without success. Any help would be appreciated!

.js:

var App = angular.module('plunker', [])

.controller("testCtrl", function($scope){
    $scope.units = "Houses";
    mockreport = {"COLUMNS":["People","Units"],"DATA":[[101,"{{units}}"],[100,"test 2"]]};
    $scope.reportData = mockreport;
})
.directive('testdirective', function($compile,$parse,$interpolate){
    return{
      restrict : 'E',
      scope:{  
        units:'@',
        reportData:'='
      },
      templateUrl:'table.html',
      link: function (scope, $el, attrs) {
        curHtml = $el.html();
      recompiledHtml = $compile(curHtml)(scope);
      //$el.html('');
      //$el.append(recompiledHtml);
    }
    };
});

index.html:

 <div data-ng-controller="testCtrl">
   <div class="panel panel-default">

      <testdirective report-data="reportData" units="{{units}}">

      </testdirective>

   </div>
</div>

table.html:

<h4>units: {{units}}</h4>
<table>
  <thead>
     <tr>
        <th data-ng-repeat="header in reportData.COLUMNS" data-ng-class="header">{{header}}</th>
     </tr>
  </thead>
  <tbody>
     <tr data-ng-repeat="column in reportData.DATA">
        <td data-ng-repeat="val in column">{{val}}</td>
     </tr>
  </tbody>
</table>

Answer №1

The binding property contains a string that is actually an Angular expression {{units}}. However, Angular doesn't recognize it as such; to Angular, it's just a regular string to be displayed on the DOM. To resolve this, you can utilize the $interpolate service to evaluate any expressions within the string and replace them with their actual values. Here’s an example:

interpolate("ABC {{units}}DEF")(scopeOrAnyObject)
will result in "ABC VALUEOFUNITSDEF"

In your specific case, for a basic demonstration, you could implement the following:

scope.getValue = function(value){
   return angular.isString(value) ? $interpolate(value)(scope) : value;
}

Then, you can use it like so:

 <td data-ng-repeat="value in column">{{getValue(value)}}</td>

Plnkr

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

Chrome on OSX Mavericks threw a RangeError because the maximum call stack size was exceeded

While attempting to run an Angular app using linemanjs in Chrome on a Mac, I encountered the following error: Uncaught RangeError: Maximum call stack size exceeded An interesting observation is that the site functions properly on Chrome on a Windows mach ...

Implement a variety of HTTP response codes for a REST endpoint

I'm currently utilizing express to serve the REST API endpoints for a simulated backend. One of the endpoints requires the ability to return different HTTP response codes, while maintaining a 200 status for the other endpoints. Here is a snippet of my ...

It's recommended to utilize the callback feature with setLoggedIn to ensure the previous state is captured effectively, as illustrated below:

To ensure capturing the previous state when using setLoggedIn, it is recommended to utilize the callback option. This will help in keeping track of changes and ensuring smoother functionality: ...

Using jQuery to scroll within a table

I am currently working on a project that involves displaying specific data rows. To achieve this, I have decided to use a table. For a better understanding, you can check out a table demo here. The issue I am facing is that whenever I change the selected ...

An issue arose when attempting to submit data from an AngularJS form

I am having an issue with my AngularJS form that is supposed to post data to a Scalatra servlet. Unfortunately, when the form is submitted, I am unable to retrieve any form parameters in my Scalatra servlet. Here is a snippet of my code: AngularJS $scop ...

Inquiries about JavaScript and the YouTube API

Being very resourceful, I am currently exploring ways to feature my YouTube links on my website in an elegant manner. Tired of the redundancy of posting on both platforms, I am seeking a solution that seamlessly integrates these posts. Despite my efforts, ...

Using jQuery to apply a class based on JSON data

This file contains JSON data with details about seat information. var jsonData = { "who": "RSNO", "what": "An American Festival", "when": "2013-02-08 19:30", "where": "User Hall - Main Auditorium", "seats": ["0000000000000000001111111 ...

Having trouble showing array data in AngularJS

I am facing an issue with displaying the data from an array in a printout. Here is the array: {{orders}} = [{"item":"DELL","quantity":6,"price":144}, {"item":"Samsung","quantity":3,"price":3131}, {"item":"222222","quantity":1,"price":31}, ...

Tips for manipulating observableArray information retrieved through the $.getJSON method

Recently, I've started using knockout.js and I'm really enjoying it so far! While working in MVC4, I encountered a small issue. I had successfully implemented kojs with static data, but now I need to work with data passed from a controller via JS ...

Striped shadows in React Three Fiber

Currently in the process of developing a basic 3D object viewer website using Next.js and React-Three-Fiber. Everything was running smoothly until I added a DirectionalLight instance and attempted to make all meshes receive shadows. https://i.sstatic.net/ ...

Guide: How to transfer the output from MongoDB in Node.js to AngularJS?

Currently, I am using Node.js to query my data from a MongoDB database. However, I am facing an issue where the data is not being sent out as expected when running this particular function. var findIco = function(db, callback) { var cursor = db.collec ...

Steps for closing a modal popup in Asp.NET WebForms after saving data

I have implemented javascript code on my main page that triggers a popup when a link is clicked: <script language="javascript"> function OpenResidentialAddressWin(subscriberContactRelationGid, routeId, btn) { window.showModalDialog("Subscribe ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

Tips for fixing the issue of "module ./response not found" in Node.js Express

Whenever I execute the command $ npm start this error message appears > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8feefcfce6e8e1e2eae1fbbccfbea1bfa1bf">[email protected]</a> start > nodemon server.js ...

I encountered an unexpected issue when attempting to retrieve my TAG in Prisma, resulting in an undefined value

Currently diving into the world of CRUD operations in NextJS using TypeScript and Prisma with TanstackQuery. I am facing an issue where I am trying to display the tag.name, but unfortunately, I keep encountering an undefined error when attempting to fetch ...

NgMaps Central is experiencing issues with the Dynamic Point functionality

I am currently utilizing NgMaps in my Angular application I am attempting to assign the center point dynamically, but it seems to be taking some other points that I have not specified: HTML: <ng-map zoom="5" center="{{center}}" style="height:600px"&g ...

Can you outline the distinctions between React Native and React?

Recently delving into the world of React sparked my curiosity, leading me to wonder about the distinctions between React and React Native. Despite scouring Google for answers, I came up short on finding a comprehensive explanation. Both React and React N ...

Enhance your Next.js application with beautifully styled formatting using prettier

Looking for some assistance in setting up prettier with my next.js project. I have the following configuration defined in my package.json file: "scripts": { "format": "prettier --write \"**/*.{js, jsx}\"", }, My project structure includes sever ...

What is the method for adding data to a table without utilizing an ID field?

Here is the code I have written: This table contains details of the candidates: <table id="candidates-table" class="table table-striped table-bordered"> <thead class="thead-dark"> <tr> <th scope="col">Candidate Picture ...

Printing with Scalable Vector Graphics (SVG) Technology

I have a unique challenge with an SVG file of a flat displayed in my browser - I need to print it out at a specific scale. I've been using SVG.js to manipulate the content, but I'm struggling to find the right combination of viewport and viewbox ...