Using local variables from an external HTML file within an AngularJS directive template

Just making sure I am wording my question correctly, but I have not been able to find any information on this specific topic. Imagine I have an AngularJS directive that looks something like this:

angular.module( 'example', [] ).directive(
        'exampleDirective', ['$compile', '$http',
        function($compile, $http) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {

                    var listOfItems = attrs.listOfItems;
                    var foo = attrs.foo;
                    var template =
                        '<ul>' +
                            '<li ng-repeat="item in ' + listOfItems + '">'+
                                '<i ng-click="clicked(item)">'+
                                    '{{item.' + foo + '}}'+
                                '</i>'+
                             '</li>'+
                         '</ul>';

                    element.html('').append($compile(template)(scope));
                }
             };
          }]);

The variable listOfItems is an array containing objects such as

[{'Name': 'this'}, {'Name': 'that'}]
, with foo being Name.

Now, I want to move the template into its own HTML file and load it using an HTTP call. How should the template be structured in the HTML file? Since the local variables won't be accessible in the file, I'm unsure about what needs to be adjusted. Any advice or suggestions would be greatly appreciated. Thank you.

Answer №1

Your scope variables will be accessible in the external template.

Here is the updated directive code:

angular.module( 'sample', [] ).directive(
  'sampleDirective', ['$compile', '$http',
    function($compile, $http) {
      return {
        restrict: 'A',

        // ... 

        templateUrl: 'my_new_template.html',

        // ...
      };
    }
  ]
);

my_new_template.html:

<ul>
  <li ng-repeat="product in ' + productsList + '">
    <i ng-click="selected(product)">
      {{product.' + bar + '}}
    </i>
  </li>
</ul>

Answer №2

If you want to achieve this, you can use the compile function within your directive. Here is an example in this Plunker

directive('exampleDirective', function () {
  return {
    restrict: 'EA',

    templateUrl: 'template.html',

    compile: function (element, attrs) {          
      var template = element.html()
                      .replace('#__LIST__#', attrs.listOfItems)
                      .replace('#__FOO__#', attrs.foo);

      element.html(template);

      return function link(scope, element, attrs) {}
    }
   };
});

In this code snippet, the content of the template.html file is as follows:

<ul>
  <li ng-repeat="item in #__LIST__#">
    <i ng-click="clicked(item)">{{ item.#__FOO__# }}</i>
  </li>
</ul>

Please confirm if this meets your requirements.

Answer №3

One option is to utilize $http.get within the link function to retrieve the HTML content.

Alternatively, you can include:

return {
     restrict: 'A',
     templateUrl: 'myhtml.html'

The content of myhtml file could look like this:

<ul>
    <li ng-repeat="item in ' + listOfItems + '">
        <i ng-click="clicked(item)">{{item.' + foo + '}}>
        </i>
    </li>
 </ul>

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

How can I retrieve the SID received in a different tab using MSAL.js?

I have successfully integrated MSAL into a client-side library, and things are going smoothly so far. My next goal is to enable Single Sign-On (SSO) by following the instructions provided in the documentation at https://learn.microsoft.com/en-us/azure/act ...

The modal window obstructs my view on the screen

You are working with a modal form that triggers a POST method in your controller Here is the view code: <div class="modal fade" id="agregarProducto"> <div class="modal-dialog" role="document"> <div class="modal-content"> ...

Issue with loading dynamic content on a webpage using HTML and JavaScript through AJAX

I am currently using the jQuery UI Tabs plugin to dynamically load HTML pages through AJAX. Here is the structure of the HTML code: <div id="tabs"> <ul> <li><a href="pageWithGallery.html" title="pageWithGallery">Gallery< ...

Tips on utilizing the enter key to add my <li> element to the list?

Currently, my to-do list setup requires users to click a button in order to add a new list item. I am looking to enhance the user experience by allowing them to simply hit "enter" on their keyboard to achieve the same result. Here is the JavaScript code I ...

Tips for creating a stylish scrollbar in a React Material-Table interface

Currently, I am utilizing the react material-table and looking to implement a more visually appealing scroll-bar instead of the default Pagination option. Although I have experimented with the react-custom-scroll package, it has not produced the desired ...

Converting a JavaScript string into an array or dictionary

Is there a way to transform the following string: "{u'value': {u'username': u'testeuser', u'status': 1, u'firstName': u'a', u'lastName': u'a', u'gender': u'a&a ...

Incorporate the previous page's location path into the next page using Props in Gatsby Link

My website has multiple pages with paginated lists of blog posts, each post generated from markdown using createPage(). Each page in the /posts directory displays 3 post previews and subsequent pages are numbered (e.g. /posts/2). I am trying to pass the p ...

Gulp does not work well with Android APK compilation

Greetings, I am facing an issue while trying to compile my Android app using gulp with the command: gulp --prod -p android. The problem arises when comparing the file size of the generated APK between myself and a colleague. When my colleague compiles, the ...

Guide to executing the refresh() function on a kendo-grid using an Angular controller

Currently, I'm experimenting with implementing various recommendations to refresh a kendo-grid, such as the one found on this page. The crux of the matter is that in the HTML code, I have: <div kendo-grid="vm.webapiGrid" options="vm.mainGridOptio ...

Instructions on how to trigger a function after adding HTML content to the directive

When working with the viewBannerCtrl controller and using the "customTable" directive, I encountered an issue. I am unable to access the "VBC.bannerAlert()" function from the directive even though I tried appending the code to the directive. Confusingly, I ...

Merging RXJS observable outputs into a single result

In my database, I have two nodes set up: users: {user1: {uid: 'user1', name: "John"}, user2: {uid: 'user2', name: "Mario"}} homework: {user1: {homeworkAnswer: "Sample answer"}} Some users may or may not have homework assigned to them. ...

Incorporate personalized design elements within the popup component of Material-UI's DataGrid Toolbar

I am in the process of customizing a Data Grid Toolbar component by making adjustments to the existing Grid Toolbar components sourced from Material-UI. For reference, you can view the official example of the Grid Toolbar components here. Upon clicking o ...

WebGl - Perspective skewing perspective

I've been working on implementing an oblique projection in WebGL, but I'm encountering an issue where the projection appears identical to ortho. Here's the snippet of code setting up the projection matrix: mat4.identityMatrix(pMatrix); ...

"Array.Find function encounters issues when unable to locate a specific string within the Array

Currently, I am utilizing an array.find function to search for the BreakdownPalletID when the itemScan value matches a SKU in the array. However, if there is no match found, my application throws a 'Cannot read property breakdownPalletID of undefined& ...

Error: The post request was blocked due to cross-origin restrictions

This is my unique script /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ var app=angular.module('todoApp ...

Struggling to understand the process of creating a new page in Express

I've created a file called ships.js in my routes folder: var express = require('express'); var router = express.Router(); /* GET Ships page. */ router.get('/ships', function(req, res, next) { res.render('ships', { tit ...

Is it optimal to have nested promises for an asynchronous file read operation within a for loop in Node.js?

The following Node.js function requires: an object named shop containing a regular expression an array of filenames This function reads each csv file listed in the array, tests a cell in the first row with the provided regular expression, and returns a n ...

Combining multiple JSON strings into a single object using JavaScript

I am facing an issue with parsing a JSON output that contains two strings with specific formats: [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}] [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","senso ...

function called with an undefined response from ajax request in React

Hello, why am I getting the response "callback is not defined"? Component 1: console.log(getUserGps()); Component 2: import $ from 'jquery' export const getUserGps = () => { $.ajax({ url: "https://geolocation-db.com/jsonp", ...

Steps to display a JSX component stored in a variable

Presently, I am implementing an if/else statement within my code to determine the content that will be displayed in the JSX element named 'signupMessage'. Subsequently, I render the contents of this 'signupMessage' element. render() { ...