Utilize interpolation with ES6 and an Angular 1.4 directive

Currently experimenting with the unique ES6 + Angular combination and facing a challenge in interpolating an html string within a directive that includes scope bindings.

We have attempted the following approach:

Current scenario

The code below is functional, but it relies on a filter instead of a directive.

HTML snippet

 <div class="thumbnail-body">
     <div ng-bind-html="vm.labels.hello | interpolate:this"></div>
 </div>

Filter within module (traditional angular without ES6)

//TODO: .filter('interpolate', () => new InterpolateFilter())
.filter('interpolate', function ($interpolate) {
  return function (text, scope) {
    if (text) {
      return $interpolate(text)(scope);
    }
  };
});

We aim to migrate the interpolation logic into a directive to eliminate the need for filters on multiple elements.

Functional but cumbersome setup

HTML snippet

<interpolate value="vm.labels.hello"  scope="this"></interpolate>

Directive

class InterpolateDirective {
  constructor() {    
   this.template = '<div ng-bind-html="value |interpolate:scope"></div>';
   this.restrict = 'E';
   this.scope = {value: '=',scope:'='};
  }
}
export default InterpolateDirective;

Module

.directive('interpolate', () => new InterpolateDirective())

Desired setup (work in progress)

HTML snippet

<interpolate value="vm.labels.hello"></interpolate>

Directive

class InterpolateDirective {
      constructor($interpolate,$scope) {
      'ngInject';this.template = '<div ng-bind-html="value"> </div>';
      this.restrict = 'E';
      this.scope = {value: '='};
      this.$interpolate = $interpolate;
      this.$scope = $scope;
  }
  
  link() {
     this.scope.value = this.$interpolate(this.scope.value)(this);
  }
}
export default InterpolateDirective;

Module

.directive('interpolate', () => new InterpolateDirective())

To sum up: The goal is to successfully implement the desired setup.

Answer №1

Give this a shot:

function CreateInterpolateDirective($interpolate) {
    return {
        template: '<div ng-bind-html="value"> </div>',
        restrict: 'E',
        scope: {
            value: '='
        },
        link: function(scope) {
            scope.value = $interpolate(scope.value)(scope);
        }
    };
}

angular.module('myApp')
.directive('interpolate', CreateInterpolateDirective);

In directives, the scope is not injected as in controllers through dependency injection. Directives can access scope by using the first parameter of the link function.

The scope defined in a directive's object property is not the same as the global scope. It serves as part of the configuration to create the directive's API and isolate the 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

Tips on selecting the active color ID from a list of available color IDs

Currently, I am trying to retrieve the color ID of the active color selection. For example, if I have three colors - yellow, blue, and red - with yellow being the default color. In this scenario, I can obtain the color ID of yellow using a hidden input typ ...

``When you click, the image vanishes into thin

Could you please explain why the image disappears once I close the lightbox? Access with password: chough ...

How should callbacks be established for communication between a React app and an iframe using postMessage?

I'm encountering an issue with my website's communication with a third-party iframe. The site has three methods - login, sign, and get information - all functioning in a similar manner. I embed the third-party iframe and send a message to it usin ...

What are some methods for creating a Venn Diagram that includes data within each section using SVG, CSS, or Canvas?

I am attempting to replicate this visual representation using pure SVG, CSS, or Canvas drawing. So far, I have successfully created three circles that overlap and placed a label in the center of each one. However, I'm facing challenges when it comes t ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

What is the best way to halt a jQuery function when hovering over it?

Currently, I have a jQuery function set up to run on setInterval(). However, I am looking for a way to pause the interval when hovering over the displayed div and then resume once no longer hovering (i.e., continue cycling through the divs). Does anyone ...

Angular controller utilizing the `focusin` and `focusout` events from jQuery

Can anyone help me figure out why this piece of code is generating syntax errors in my AngularJS controller? $(".editRecur").focusin(function() { $(.recurBox).addClass("focus"); }).focusout(function() { $(.recurBox).removeClass("focus"); }); ...

What is the best way to use an AngularJs variable as an argument in a jQuery function?

Looking for some help with this jQuery function: function updateProfile(profile, sessionId){ alert(profile,sessionId); } In my HTML code, it's set up like this: <button onclick="updateProfile(profile, {{sessionId}})">Update</button& ...

When invoked within a function, Angular's ngResource will not initiate the AJAX call

I'm having an issue with making an AJAX call using ngResource. In the following code snippet, both 'a' and 'b' are printed, but the AJAX call from Table.import() is not executed. However, when I move the AJAX call outside of the on ...

Determine the amount of unused vertical space within a block of text

Having applied CSS to a span element: font-height = 120px; height = 120px; line-height = 120px; The text inside the span does not completely fill the height of 120px. Is there a method to determine the offset of the text from the top and bottom boundar ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...

Angular is not acknowledging the required fields as specified

I have a question regarding the functionality of my page. Currently, everything is working fine except for the input field for user.productNumber at the bottom. While all the other "required" fields are preventing the "Create Account" button from being e ...

What is the process for uploading files from NextJS directly from the browser to either Cloud Storage or an FTP server?

Is there a way to upload files from the browser using NextJS directly to Cloud Storage or an FTP server? I'm looking to upload files directly from the browser to a storage server. Do you think I can utilize node-ftp in the API routes of Nextjs, like ...

What is the best way to connect data so that when a user clicks on a specific card, it appears on a popup card

When a user clicks on any card containing data retrieved from a backend API GET method, that data should be displayed in a pop-up card. In my situation, I have two components: DisplayNotes.vue and UpdateNotes.vue. Whenever a user clicks on a displayed card ...

Place jQuery popup box in position

After numerous attempts, I still can't seem to find a working solution. All I want is to move my jQuery dialog box down by about 50px from the top of the page. Any suggestions on how to achieve this? function openingDialog() { $("#message").dialo ...

Please verify the utilization of jQuery.ajaxSettings.xhr

var _orgAjax = jQuery.ajaxSettings.xhr; jQuery.ajaxSettings.xhr = function () { var xhr = _orgAjax(); DoSomeLogging(); return xhr; }; I came across this code snippet and I'm trying to make sense of it. Does this mean that any $.ajax(...) ...

What is the method for obtaining the most up-to-date JSON GET request URL?

Using JQGrid with search filters and setting loadOnce=false. I perform a search in the grid and observe the JSON request URL in firebug: http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1& ...

Using a JSON string with form field names and corresponding values to automatically fill in form fields using jQuery

My JSON string looks like this: [{"meta_key":"algemeen_reden","meta_value":"oplevering"},{"meta_key":"algemeen_netspanning","meta_value":"230"}] Currently, I am using the following script to fill out form fields: // Grab Algemeen Data get_algemeen_data ...

How can I stop popup labels from appearing in MapBox GL JS when I don't want them to be visible?

Having created an application using MapBox GL JS, I have placed numerous markers all around the globe. As the mouse hovers over these markers, a description box pops up, which is what I intended. However, I am encountering an issue where these labels flick ...

Uploading video files using XMLHttpRequest encountered an error on a particular Android device

One of our testers encountered an issue where they failed to upload a video file (.mp4) on a specific Android mobile phone. Interestingly, the same file uploaded successfully on an iPhone and another Android device. To investigate further, I attempted to ...