Exploring Angular Foundation's templateUrl Property for Directives

Angular-foundation (http://pineconellc.github.io/angular-foundation/) utilizes angular directives to incorporate Foundation components like Modals, Tabs, and other front-end services.

The issue I'm encountering is that the directives come with preset "templateUrl" attributes that are not present on my server. Since this is an external dependency managed by Bower, manual updates to the library are not possible. Here's an example directive extracted from the library:

angular.module('mm.foundation.tabs', [])
    .directive('tabset', function() {
      return {
        restrict: 'EA',
        transclude: true,
        replace: true,
        scope: {},
        controller: 'TabsetController',
        templateUrl: 'template/tabs/tabset.html',
        link: function(scope, element, attrs) {
          scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
          scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
          scope.type = angular.isDefined(attrs.type) ? scope.$parent.$eval(attrs.type) : 'tabs';
        }
      };
    })

In my module, I have specified a dependency on the mm.foundation module:

angular.module('foundationDemoApp', ['mm.foundation.tabs']).controller('TabsDemoCtrl', function ($scope) {
  $scope.tabs = [
    { title:"Dynamic Title 1", content:"Dynamic content 1" },
    { title:"Dynamic Title 2", content:"Dynamic content 2" }
  ];

  $scope.alertMe = function() {
    setTimeout(function() {
      alert("You've selected the alert tab!");
    });
  };
})

Currently, I am using Gulp along with gulp-html2js for templating bundling. The github README mentions customizing templates (https://github.com/pineconellc/angular-foundation) using $templateCache, but I'm unsure how to modify the templateUrl to point to my template's location.

If anyone has any insight on this matter, I would greatly appreciate it!

Answer №1

Since no one has provided an answer yet, I'll take a shot at it. Hopefully, this information will be helpful to you, ossys (note to any moderator: feel free to remove my response if it is incorrect).

If you have used bower install to install the library, you should be able to locate those templates in the directory

bower_components/angular-foundation
. You can follow their example at https://github.com/pineconellc/angular-foundation#customize-templates to implement something similar to this:

html2js: {
  options: {
    base: '.',
    module: 'ui-templates',
    rename: function (modulePath) {
      var moduleName = modulePath.replace('bower_components/angular-foundation', '').replace('.html', '');
      return 'template' + '/' + moduleName + '.html';
    }
  },
  main: {
    src: ['bower_components/angular-foundation/**/*.html'],
    dest: '.tmp/ui-templates.js'
  }
}
//or in gulp
gulp.src('bower_components/angular-foundation/**/*.html')
  .pipe(html2js({
    outputModuleName: 'ui-templates'
  }))
  .pipe(concat('ui-templates.js'))
  .pipe(gulp.dest('./'))

Answer №2

You can use $templateCache to easily replace the template with your own custom one.

For example, for a tab, you can do the following:

<script type="text/ng-template" id="template/tabs/tabset.html" 
  src="/path/to/your/template.html"></script>

Answer №3

Thank you for the insightful input, both responses are spot on!

My issue was approaching the solution from the wrong angle. Instead of replacing the templateUrl parameter in each directive, I realized that I needed to adjust the template's filename during compilation. For instance....

Prior to incorporating angular-foundation, my templates task with gulp and html2js looked like this:

gulp.task('templates', function (cb) {

           gulp.src('path/to/tempalates/**/*.html')
             .pipe(html2js({
               outputModuleName: 'my.templates',
               base: './src/web/',
             }))
             .pipe(concat('templates.js'))
             .pipe(insert.prepend("var angular = require('angular');"))
             .pipe(gulp.dest('./src/web/'))
             .on('end', done);
         };
});

I proceeded to add the html template directory from angular-foundation's GitHub repository into the path 'path/to/foundation/template'. Then, I updated the templates gulp task to rename the 'path/to/foundation/template' path to match the one coded in the directive. For example, if a directive expects a templateUrl of 'template/tab/tabs.html' but the actual template is located at 'path/to/foundation/template/tab/tabs.html', the rename function would remove 'path/to/foundation' and keep the path as 'template/tab/tabs.html' during the build process. The revised gulp task now appears as follows:

gulp.task('templates', function (cb) {
           gulp.src(['path/to/tempalates/**/*.html','path/to/foundation/template/**/*.html'])
             .pipe(html2js({
               outputModuleName: 'my.templates',
               base: './src/web/',
               rename : function (modulePath) {
                  var moduleName = modulePath.replace('path/to/foundation/', '').replace('.html', '');
                  return moduleName + '.html';
                }
             }))
             .pipe(concat('templates.js'))
             .pipe(insert.prepend("var angular = require('angular');"))
             .pipe(gulp.dest('./src/web/'))
             .on('end', done);
         };
});

Now, all templates are compiled with the paths expected by angular-foundation, eliminating the need to manage template paths dynamically.

Hopefully, this solution proves helpful to others facing similar challenges!

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

What is the process for creating and registering custom Handlebars functions?

Despite spending plenty of time searching, I am still unable to find detailed information on where exactly to place my custom handlebars helpers. Should they be added in a <script> tag within my webpage's .hbs file? Or should I include them in a ...

What is the reason behind the NextJS Warning: "Server is sending extra attributes: data-new-gr-c-s-check-loaded..."?

Recently, my NextJS Application has been displaying the following warning message: Warning: Additional attributes received from server: data-new-gr-c-s-check-loaded,data-gr-ext-installed,cz-shortcut-listen,data-lt-installed I am uncertain as to why this ...

Error encountered while using Jest, React, Typescript, and React-Testing-Library

I have set up a project using React/NextJS with Typescript and now I am incorporating unit testing with Jest and React Testing Library. One of the unit tests for my component is as follows: import React from 'react'; import '@testing-libra ...

Transforming a React object into an array and displaying it on the frontend using the .map method

After making a single API call, I have received two different sets of data. The first set is an array containing information about various items, including their names, prices, rarity, and images. The second set consists of items with details such as condi ...

The behavior of Ajax is resembling that of a GET method, even though its intended method

Greetings, I am currently facing an issue while coding in Javascript and PHP without using jQuery for Ajax. My aim is to upload a file over Ajax and process it in PHP. Here is the code snippet: index.html <html> <head> <title>PHP AJAX ...

AngularJS real-time schedule display

Currently, I am utilizing the Twitter stream API to fetch tweets based on specific hashtags. To achieve this, my server leverages an IO socket through which the client receives incoming messages: socket.on('tweet', function(msg) { ...

Error: Invalid syntax detected: /blog

I am encountering an issue with jQuery while trying to add a blog section to my existing single-page site. The new blog will be located in a separate /blog directory, causing the menu item for it to differ from the other href="#" tags on the index.html pag ...

Create a dynamic HTML page using JavaScript

When I click on the following links: How can I create a new page using JavaScript? Create and dynamically append elements I'm looking to dynamically add HTML elements with JavaScript within a div, but I don't want my code to become overly comp ...

Retrieve the store location value when clicked (Javascript)

I'm currently struggling to capture the value of a click in my Javascript code and I could use some help understanding how to achieve this. <span class="s-link"> <a class="s-link-pim-data" href="javascript:void(0);" target="_blank" title="O ...

Using Passportjs for user authentication with Angularjs (resource/http get)

I am currently experimenting with integrating Passportjs into an Angular and Express project. My current focus is on testing the Facebook strategy in passportjs. While authentication appears to be successful, I am encountering an issue where it does not n ...

Error: The generated Yeoman AngularJS app is encountering an issue with an unidentified provider named 'aProvider'

After creating my AngularJS application using the Yeoman AngularJS generator, everything was running smoothly with the original source code. However, when attempting to run the app from the 'dist' folder generated by the Grunt build, an error oc ...

What steps should be taken to make mocha utilize the HTTP response?

Every time I make an http call, the function it returns causes my comparison to fail because [Function] is never equal to the value I want. Is there a way to make my assert statement consider the true/false flag within it? # test/helloWorld.js const othe ...

When I click on the button, the page reloads instead of executing the essential code

On my website, there is a settings page where users can edit their profiles. After editing, they click the update button which triggers the updateProfileData function. This works smoothly in Chrome browser, but in Firefox, the page reloads as soon as the b ...

The event listener for browser.menus.onClicked is dysfunctional in Firefox

Currently, I am in the process of developing my own Firefox extension and I have encountered an issue with adding a listener to an onclick event for a context menu item. manifest.json { "manifest_version": 2, "name": "My exten ...

Guide on displaying a dropdown in AngularJS when the select option is already applied but not showing

I am currently working on creating a select option using JSON data, but for some reason it is not displaying. I have used the select tag and placed the option tags inside it. <div ng-switch-when="SWITCH"> <select name="selectedFacilit ...

JavaScript - Executing the change event multiple times

Below is the table I am working with: <table class="table invoice-items-table"> <thead> <tr> <th>Item</th> <th>Quantity</th> <th>Price</th> & ...

Distinguishing Js versus Jsx

While working on React JS, a question came to mind. In the code below, both JavaScript (JS) and JSX are used, and they seem to respond similarly. So, why should we specifically use JSX? After searching online, I found information about the differences bet ...

JavaScript Alert: The Ajax XMLHttpRequest Response has Returned Null

Below is the code snippet: <script type="text/javascript"> var xmlhttp; $(document).ready(function (){ xmlhttp=new XMLHttpRequest(); ...

Utilizing loops to generate multiple arrays from a given string

I have a sequence of values: "000111111122222223333333444455556666" Is it possible to utilize three separate loops to generate multiple arrays based on different index ranges? For instance, producing an array from index 0 to 3 ([000]), then creating arr ...

Is there a way to use AJAX for transferring a value?

I am looking to transmit a value to a php-script (servo.php) that will then write the received data in a file (/dev/servoblaster). The script section of my HTML file (index.html): <script> function tiltt() { var tilt = document.getElementById("tilt ...