What methods are available to adjust the templateURL of my directive according to the values in its controller?

In the AngularJS directive and controller below, I want to dynamically set the `templateURL` based on values of integers `aB` and `aC` in the associated controller.

If the sum of `aB + aC` is greater than or equal to 10, I want it to use `foo.html`; otherwise, I want it to use `bar.html`. How can this be achieved?

myApp.directive('myDirective',function(){
    return {
      restrict:'E',
      scope: {
        myObject: '='
      },
      controller: 'myDirectiveCtrl',
      controllerAs: 'myDrCtrl',
      bindToController: true,
      template: 'aB={{myDrCtrl.myObject.aB}} aC={{myDrCtrl.myObject.aC}}'

    };
  }
);

myApp.controller('myDirectiveCtrl', function($scope){
    var self = this;
    $scope.$watch(function() {return self.myObject}, function (objVal) {
        console.log("watch fired");
        console.log('objVal.aB = ', objVal.aB);
        console.log('objVal.aC = ', objVal.aC);
    },true);

});

Answer №1

template/templateUrl option of a directive undergoes evaluation prior to the creation of the directive scope. As a result, accessing scope variables within the templateUrl function is not possible.

However, this issue can be resolved by utilizing the ng-include directive in which an expression can dynamically generate a URL based on the values of scope variables.

Custom Directive

myApp.directive('myDirective',function(){
    return {
      restrict:'E',
      scope: {
        myObject: '='
      },
      controller: 'myDirectiveCtrl',
      controllerAs: 'myDrCtrl',
      bindToController: true,
      template: '<ng-include src="(aB + ac >= 10) ? \'foo.html\': \'bar.html\'"></ng-include>'
    };
  }
);

Answer №2

If you want to implement ngInclude, you can try the following approach:

myApp.directive('includeDirective',function(){
    return {
      restrict:'E',
      scope: {
        includedObject: '='
      },
      controller: 'includeController',
      controllerAs: 'incCtrl',
      bindToController: true,
      template: '<div ng-include="includedObject.filePath"></div>'
    };
  }
);

myApp.controller('includeController', function($scope){
    var self = this;
    $scope.$watch(function() {return self.includedObject}, function (objectValue) {
         objectValue.filePath = 'example.html';
         if(objectValue.valueA + objectValue.valueB >= 10){
             objectValue.filePath = 'sample.html';
         }
    },true);
});

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

Slide your finger upwards to shut down the mobile navbar in bootstrap

Hey there, I'm currently developing a website using Bootstrap framework v3.3.4. I have a mobile navbar that opens when I click a toggle button, but I would like it to slide up to close the navigation instead. Here is an image showing the issue Do y ...

What is the process for attaching the stack when initializing and throwing errors separately in JavaScript?

In all the documentation I've read, it consistently advises to both throw and initialize errors on the same line. For example: throw new Error("My error"); But what if you were to first initialize the error and then throw it on separate lines? For ...

Issue with child component display

I cannot figure out why my component is not appearing on the page at all. It shows up as <signinform></signinform>. Even though I am using react-form, I don't think that is the reason for it not rendering. signin.js import React from &ap ...

There seems to be a glitch in the functionality of annotations when using annotator.js

Currently, I am utilizing annotator.js to store the range in mysql. The following code fragment is being used for highlighting text within my file: <script src="/js/pdfjs/annotator.js"></script> <script> $(function(){ var annotation ...

Leveraging the Power of Email with Javascript and Ajax

I have encountered an issue with using ajax to send emails. Specifically, when I retrieve the value from the message box, it does not retain any line breaks. I am seeking a solution that will allow me to capture the email contents without losing their or ...

What is the best way to include an attribute to an object in a knockout observable array and ensure a notification is triggered?

Implementing Knockout.js in my project, I have an observable array included in the view model. function MyViewModel() { var self = this; this.getMoreInfo = function(thing){ var updatedThing = jQuery.extend(true, {}, thing); ...

Unable to locate the issue: angular.js:38 Unhandled Error: [$injector:nomod]

Can someone please assist me in resolving this error? I have been struggling to fix this problem. \layout\sidenav.controller.js angular.module('app.layout', []) .controller('SideNavController', SideNavController); function ...

"The seamless integration of Ubergallery with AJAX functionality creates a

When I attempted to access the Ubergallery through an Ajax call, I encountered numerous issues that I was able to resolve using the script provided below. However, despite resolving most of the problems, I am now facing a new issue - the navigation buttons ...

Is there a way to restrict keyboard input on this date picker?

Can you review the following link and let me know which properties or events I should utilize in this scenario? https://codesandbox.io/s/charming-frost-qrvwe?file=/src/App.js ...

Dynamic resizing in NextJs does not trigger a re-render

My goal is to dynamically pass the width value to a component's styles. Everything works fine on initial load, but when I resize the window, the component fails to re-render even though the hook is functioning as intended. I came across some informat ...

View duplication issue in Laravel occurs when a dropdown option is selected multiple times

I am experiencing an issue with my Laravel view. I am successfully retrieving data through ajax and displaying it in my view. However, when I select something from a dropdown, the data appears but the layout gets duplicated. Upon inspecting the console, ...

Steps to open and configure a Mobile-Angular modal from another controller

Is it possible to use a modal in Angular JS for mobile devices without compromising the layout? I'm having trouble setting up the controller for my modal inside my main controller and passing parameters. Should I consider using ui-bootstrap for this p ...

The issue of file uploading not functioning properly with AngularJS on a lighttpd server is causing frustration

Currently in my project, we are utilizing the lighttpd server. I am attempting to upload a file and encountering two Response Headers. The first has a 301 status code (Moved Permanently) and the second has a 200 status code (OK). However, upon checking th ...

Error: The route configuration must include a "path" parameter when exporting imports in Vue Router

Important Information: The Index/Search/Features modules all share the same code structure, with different names. Each module consists of a path, component, name and meta as seen below. notes/routes/routes.js import Index from './index' import ...

Loading large amounts of data efficiently with Angular and Firebase

Currently, I am utilizing AngularJS in conjunction with Firebase. Objective: My aim is to showcase all the information stored within my Firebase database (which consists of a fixed number of approximately 1600 items). Challenge: The issue at hand is that ...

Elements positioned next to each other with no margin when spread across multiple lines

I have a color picker with a right margin of 6px. https://i.sstatic.net/OHqQK.png I need the white square (with the black check marker) to not have a right margin so it doesn't wrap to the next line and can use the full width. Instead of applyin ...

During the present module, retrieve the runtime list of all modules that are directly imported (Javascript/Typescript)

Imagine you have a set of modules imported in the current module: import {A1, A2, A3} from "./ModuleA"; import {B1, B2, B3} from "./ModuleB"; import {C1, C2, C3} from "./ModuleC"; function retrieveListOfImportedModules() { // ...

processes that are repeatedly called

<li class="cart_item clearfix" v-for="(product, index) in products" :key="index"> <div class="cart_item_text"><button type="button" class="btn btn-success" name=&q ...

Ways to execute a method inside a constructor

I've been struggling to find a solution to my question because most of the responses I come across are too advanced for my beginner level understanding of JavaScript. Below is the code snippet I am working with: function xyPoint(x, y){ this.x = ...

Guide to Incorporating a Marker into an SVG Blinking Rectangular or Circular Border Image on Google Maps

I have a link that points to a specific location on Google Maps using latitude and longitude: http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png Now, I am looking to add a blinking border to this marker link. Is there a way to achieve this ...