Using dynamic template URLs in resolving with Angular's UI-Router can provide flexibility

Currently, I have implemented a parent directive for an entire view to interchange templates based on the outcome of a promise.

.directive('myDirective', function(myService) {
    var rootDir = '/path/to/templates';

    return {
         restrict: 'E',
         replace: true,
         controller: controller,
         link: linker,
         template: '<div ng-include="getContentUrl()"></div>'
    };

    function controller($scope) { ... }

    function linker(scope) { 
        myService.getData().then(function(res) {
            scope.getContentUrl = function() {
                var tpl = res.status >= 400 ? '/tplContent.html' : '/tplError.html';
                return rootDir + tpl; 
            };
        });    
    }
})

Yet, it would be more efficient if I could execute myService.getData() while resolving my angular-ui route and dynamically load the templateUrl once my promise is fulfilled.

Answer №1

Have you thought about storing the output of getData() in the scope and binding to it?

template: '<div ng-include="{{contentUrl}}"></div>'

function linker(scope) { 
    myApiClient.fetchData().then(function(response) {
        var determineContentUrl = function() {
            var template = response.code >= 400 ? '/errorTemplate.html' : '/successTemplate.html';
            return baseUrl + template; 
        };

        $scope.contentUrl = determineContentUrl();
    });    
}

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

Transforming a JSONP request to automatically parse a text response into JSON

If I have the following request $.ajax({ type: "GET", dataType: "jsonp", jsonp: "callback", jsonpCallback: "my_callback", url: my_https_url, headers:{"Content-Type":"text/html; charset=utf-8"}, success: function(data) { ...

What steps do I need to take to set up Vue-CLI 3 to generate a webpage with no JavaScript?

My dilemma is this: I have a simple static page that does not require JavaScript. Using vue-cli 3, I am attempting to pass the HTML file through webpack for minification purposes. Unfortunately, it seems that accomplishing this task is not as straightforwa ...

Easily upload files using Multer without the need for specifying action, method, or encrypt="multipart/form-data" attributes in the form tag

I'm currently facing an issue while trying to upload an image using Multer and Angular's $http.post method. Instead of triggering the form submission with a submit button, I want to directly use $http.post. However, I am encountering a problem wh ...

What is the best way to show only one div at a time when selecting from navbar buttons?

To only display the appropriate div when clicking a button on the left navbar and hide all others, you can use this code: For example: If "Profile" is clicked in the left navbar, the My Profile Form div will be displayed (and all others will remain hidde ...

Updating the database table using javascript

I am looking to dynamically update my database based on a condition in JavaScript. Currently, I have been using the following approach: <a href="#" onclick="hello()">Update me</a> <script> function hello(smthing) { if(smthing == true) ...

What is the process for establishing a dependency on two distinct JavaScript files, similar to the depends-on feature found in TestNG?

I am faced with a scenario where I have two separate JS files containing test methods, namely File1 and File2. The requirement is that File2.js should only be executed if File1.js has successfully completed its execution. My current setup involves using ...

Using Angular JS, the JSON method is invoked from a location external to the controller

How can I call an inner method from outside a controller in AngularJS? var app; (function (){ app = angular.module("gallery", []); app.controller("galleryController", ['$scope','$http', function($scope, $http){ var gallery = this; ...

What is the best way to display the elements of an array within an HTML div element?

I've been trying to display the contents of an array in a div container on my HTML file, but I'm stuck. Here's what I currently have: function printArray() { var $container = $('.container'); $container.html(''); ...

What is the process for creating a transparent default color theme in MUI?

I'm looking to make an element's background color the primary main color with some transparency using Material-UI. I've attempted a couple of methods, but unfortunately neither have worked for me. Any suggestions or guidance would be greatly ...

Creating a dynamic CSS height for a div in Angular CLI V12 with variables

Exploring Angular development is a new venture for me, and I could use some guidance on how to achieve a variable CSS height in Angular CLI V12. Let me simplify my query by presenting it as follows: I have three boxes displayed below. Visual representatio ...

Is it possible to determine the outcome of a JavaScript function using Python?

I am currently in the process of creating a web crawler. Extracting links from HTML is simple, but finding links that are generated by JavaScript proves to be more challenging for me. Is there a way to access the JavaScript output in order to determine w ...

Establish a timeout for the Material UI drawer to close automatically after being opened

I am looking for a way to automatically close the drawer after a specific duration, but it seems that material UI drawer does not have the necessary props for this. Is there a workaround using transitionDuration or perhaps adding a setTimeout in my functio ...

Managing Import Structure in Turborepo/Typescript Package

I am currently working on creating a range of TypeScript packages as part of a Turborepo project. Here is an example of how the import structure for these packages looks like: import { Test } from "package-name" import { Test } from "package ...

Having trouble with enabling HTML5 mode to true on an Angular frontend and Laravel backend

I successfully removed the "#!" from my website URL and everything is working perfectly. The only issue I am facing is that when I try to reload a sub URL other than the home page, it shows a "page not found" error. However, I am able to access the same s ...

Using the comma separated values as the final parameter in the ng-repeat loop

In my select element, I am utilizing ng-repeat to generate options. My goal is to include a final option labeled All, which should display the comma-separated values of all the other options. <select ng-model="facilityIdForEquipment" ng-change="loadFa ...

Tips for refreshing the tawk.to widget when the language changes with the help of i18next

Utilizing i18n-jquery for language switching and integrating the tawk.to chat widget, I've successfully loaded different languages on page reload. However, due to i18n not refreshing the page (which I don't want to do), I need to figure out how t ...

Building Dynamic Forms with React.js and Bootstrap for Easy Input Field Management

In the process of developing a web application using React.js and react-bootstrap, I encountered an interesting challenge. On one of the form pages, users should be able to input symptoms of an illness they are dealing with. The key functionality required ...

Is there a way for me to intercept JavaScript code before it runs on Chrome?

Looking to develop a Chrome extension for the developer tools that can intercept JavaScript code on a current web page prior to compilation or execution by the browser. I aim to instrument the JS code before it runs in the browser. Could someone assist wi ...

Making an Ajax request with JSON is yielding unexpected variables that cannot be modified or removed

Attempting to make an AJAX call using a script: $.ajax({ url: pageURL, data: loadData, type: 'POST', cache: false, dataType: 'json', success: function (data) { //if the call was successful console.log(su ...

JavaScript code does not seem to be functioning properly on my computer, but it works perfectly fine on

While the code functions perfectly in JSFiddle, it seems to fail when I try to implement it in an HTML file. Despite my efforts, I am unable to pinpoint the source of the issue. If you'd like to view the working version, here is the Fiddle demo. Bel ...