Exploring ways to dynamically alter templates using the link function in Angular.js

Recently, I developed a directive called widget which functions similar to ng-view, but the template name is derived from an attribute.

app.directive('widget', function() {
    return {
        restrict: 'EA',
        scope: true,
        templateUrl: function(tElement, tAttrs) {
            var page = tAttrs.name + ".html";
            return window.location.href.replace(/[^\/]+$/, '') + page;
        }
    };
});

It operates successfully when I use it in this manner:

<widget name="page"/>

This will display page.html. However, using the following code snippet will not work (I understand that it will result in a 404 error until the input is completed, but this serves as an example):

<input ng-model="widgetName"/>
<widget name="{{widgetName}}"/>

In order to achieve a dynamic widget, I believe I need to construct a template using the link function. How can I accomplish this? I only know that I need to create a scope using {name: '@name'} to bind it with the attribute name and that I can utilize $http in the link function, but I am unsure of what steps to take once I retrieve the page from it.

Answer №1

To achieve a dynamic templateUrl, you can utilize ngInclude by binding it to the variable widgetName. Here's how:

<div ng-include="widgetName"></div>

This approach requires that widgetName contains the entire path. For more advanced functionality, such as appending '.html' to the widget name and monitoring changes using $scope.$watch on widgetName, you can wrap it in a directive like below:

app.directive('customWidget', function() {
    return {
        restrict: 'EA',
        scope: {
            widgetName : '=name'
        },
        controller: function($scope) {
            $scope.$watch('widgetName', function() {
                $scope.templateUrl = $scope.widgetName + '.html';
            });
        },
        template: '<div ng-include="templateUrl"></div>'
    };
});

For implementation in HTML:

<input ng-model="widgetName"/>
<custom-widget name="widgetName"/>

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 Bootstrap dropdown not activating the click event?

My issue involves a Bootstrap dropdown where the click event is not triggering. I'm curious about why the click event won't trigger and if there's a solution available to fix this problem. <div class="dropdown d-inline-block"> ...

Displaying AngularJS content as text in an HTML file

I have been learning from the AngularJS Tutorial on Code School, but I'm experiencing an issue where my JavaScript code is not rendering properly in the HTML. Below is the snippet of HTML code: <html ng-controller="StoreController as store"> & ...

Instructions for creating a JavaScript click function that iterates through all records, not just the initial record

Although I'm new to web development and still learning the basics of html, javascript, etc., I have a problem that seems quite simple. The challenge lies in understanding javascript functions, which I find particularly tough to grasp. Here's what ...

Leverage ConvexGeometry within the npm release of THREE

Is there a way to utilize ConvexGeometry in the npm version of THREE? It appears that it was introduced in r85: https://github.com/mrdoob/three.js/releases I noticed that it's only present in the example folder. Is there a method to incorporate it ...

Using Angular JS to connect Promises while preserving data

There have been discussions about chaining promises, but this scenario presents a unique challenge. I am currently working on making multiple http get requests in my code. The initial call returns an array, and for each object in this array, another http c ...

utilizing the .on method for dynamically inserted elements

I have a code snippet that triggers an AJAX request to another script and adds new <li> elements every time the "more" button is clicked. The code I am using is as follows: $(function(){ $('.more').on("click",function(){ var ID = $(th ...

Can someone assist me in creating a clickable link that opens a menu in HTML when clicked?

I have been attempting for the past few days to open the megamenu by clicking on a link, but despite my efforts, I have not been successful. After reviewing some code, I discovered a clue in the CSS. It seems that setting the visibility value to visible wi ...

Unexpected Error: Null value prevents accessing 'getElementsByClassName' property in HTML, along with Troubleshooting Inactive Button Behavior in HTML

Can someone identify the error in my HTML code? I keep getting an "Uncaught TypeError: Cannot read property 'getElementsByClassName' of null" error on the second line of the script tag. Additionally, my implemented active header code is not funct ...

Although hiding and showing elements in jQuery is quick, the rendering engine is too sluggish

Experiencing a performance problem when toggling the visibility of all "tr.content" elements within a complex dom structure like this:    <tbody class="collapsible">        <tr class="handler">            <td>Collaps ...

Creating a Border Length Animation Effect for Button Hover in Material-UI

I'm currently exploring Material-UI and trying to customize a component. My goal is to add a 'Border Length Animation' effect when hovering over the button. Unfortunately, I have yet to successfully implement this animation as intended. For ...

Guide to dynamically insert rows in HTML using Vue.js based on the selected option

This is the initial row. Depending on the selection made here, different rows will be displayed <div class="row"> <div class="col-md-4"> <div class="form-group label-floating"> <label class="control-label">Case Type< ...

Encountering a 404 error when typing a link and refreshing the page in Laravel combined with VueJS

I encountered an issue while working on a Laravel VueJS application for our Proof of Concept (POC). I have integrated vue-router into the project and it is functional. However, whenever I attempt to navigate to a specific page defined in the routes of app. ...

What are the possible arguments for the event type onInput?

While diving into the world of html / javascript / vue, I stumbled upon the following code snippet. <input type="text" onInput="doAction(event);"> <script> var mesdata = { message: 'type your m ...

The initial ajax request successfully connects to the file, but encounters a 404 error upon the second attempt

I am currently encountering an issue with a jQuery post function. The function is designed to run multiple times and then stop, which it has successfully done in the past. However, now the problem arises when the function tries to execute itself again afte ...

Transforming field names in JSON using AngularJS $resource

I am currently working on an AngularJS project that interacts with data through an API. During the implementation of the 'create' functionality using $resource, I encountered a challenge with naming conventions. While I use camelCase, the API onl ...

Using jQuery to dynamically include option groups and options in a select box

Generate option groups and options dynamically using data retrieved via AJAX. <select name="catsndogs"> <optgroup label="Cats"> <option>Tiger</option> <option>Leopard</option> <option>Ly ...

Refreshing the Angular page using ng-route in html5 mode fails to redirect to index.html

My goal is to implement html5 mode for my mean app. Below is the view router code in my angular script: app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider // define r ...

Are you familiar with the Pagination and Card Components offered by Ant Design (antd)?

Can you merge the Pagination feature from antd with Card components to create a layout resembling Pinterest, complete with pagination? The standard Pagination code from https://ant.design/components/pagination/: import { Pagination } from 'antd&apo ...

Having trouble adding/removing/toggling an element class within a Vue directive?

A successful demonstration can be found at: https://jsfiddle.net/hxyv40ra However, when attempting to incorporate this code within a Vue directive, the button event triggers and the console indicates that the class is removed, yet there is no visual chang ...

Vuetify's v-badge showcasing an exceptionally large number in style

Encountering an issue with using v-badge and v-tab when dealing with large numbers in a v-badge. Managed to find a CSS workaround by setting width: auto; for adjusting the size of v-badge to accommodate huge numbers, but now facing an overlap with my v-ta ...