Hook on UI-Router that triggers after the template has been retrieved and added to the DOM

We are faced with the challenge of supporting a legacy module that requires synchronous code to run after templates have been fetched and attached to the DOM.

As we transition from our custom router to UI-Router, we have successfully resolved the route and fetched the templates. However, we are struggling to find a way to hook into the process after the templates are loaded.

Project Details:

  • UI-Router: 1.0.0-rc.1
  • Angular: 1.5.8

We have experimented with the onSuccess hook, where we return a resolved promise and chain it with a then callback. Unfortunately, this approach is still within the transition lifecycle and the templates have not yet been attached to the DOM. The same issue persists when utilizing resolve blocks in the state definition.

Although using a timeout after onSuccess does work, it is not the ideal solution.

While we do have redux-ui-router at our disposal, dispatching a thunk when onSuccess is triggered would require additional refactoring for the older module.

If you have any insights or suggestions on how to address this issue, we would greatly appreciate it.

Thank you!

Answer №1

You're making progress by utilizing the onSuccess method. This hook is triggered when a state-machine transition is successfully completed. UI-Router effectively syncs views using the onSuccess method with the default priority set to 0. Once the views are synced, the templates are compiled and inserted into the DOM.

By setting up an onSuccess hook with a slightly lower priority, your hook will be executed after the view syncing process is completed.

app.run(function($transitions) {
  $transitions.onSuccess({}, yourhook, { priority: -1 } )
});

It's important to note that AngularJS template rendering is inherently asynchronous due to the digest loop.


Check out this plunker that showcases both points:

  • debugger statements are placed before and after view synchronization

  • template variable interpolation occurs only after the digest cycle finishes

http://plnkr.co/edit/OpKexobSQ6WTrP87k4Tb?p=preview

Answer №2

Even though Chris T provided a great solution for fetching a single template, we needed to fetch multiple templates. In the end, we decided to utilize the resolve block.

resolve: {
            templates: ['$q', '$templateRequest', function ($q, $templateRequest) {
                    return $q.all([
                        $templateRequest('../template2.html'),
                        $templateRequest('../template3.html')
                    ]);
                }]
        },

After that, we initialized the process upon successfully resolving the promises.

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

Achieve top-notch performance with an integrated iFrame feature in Angular

I am trying to find a method to determine if my iframe is causing a bottleneck and switch to a different source if necessary. Is it possible to achieve this using the Performance API? This is what I currently have in my (Angular) Frontend: <app-player ...

AngularJS Error: Attempting to Access Undefined Object - Jasmine Testing

Encountering an error while running Jasmine tests when trying to mock/spy on an API call in the tests. Below is the code snippet responsible for calling the API: UploadedReleasesController.$inject = ['$log', '$scope', '$filter&apo ...

Can the AngularJS icon adapt to different lists?

I'm currently developing in AngularJS / Jade and I need to implement functionality where an icon changes when a user clicks on something. The code I have right now looks like this: a(onclick='return false', href='#general', data-t ...

The absence of the 'Access-Control-Allow-Origin' CORS header was noticed in the response from the Wikipedia API

Attempting to retrieve data from the Wikipedia API using axios in reactJS. Here is my request: axios.get('https://en.wikipedia.org/w/api.php?action=opensearch&search=lol&format=json&callback=?') .then((response) => { c ...

Nested ngInclude causing binding to fail

I am managing a list of tasks that may have subtasks and I need to display only the root level initially. Users can then load each branch as needed. To achieve this, I am utilizing nested ng-includes and ng-init to pass the task list. Below is the template ...

Headers with a 3 pixel stroke applied

I have a design on my website that includes a 3px stroke around the header text to maintain consistency. I don't want to use images for this due to issues with maintenance and site overhead. While I know about the text-stroke property, browser suppor ...

VueJS: components unable to access global variables

I am currently in the process of transitioning my front-end to a gulp-based application. I seem to be encountering some issues with Vue.js as I am facing two errors: [Vue warn]: Property or method "params" is not defined on the instance but referenced dur ...

Is there an official IRC channel for YUI?

Although the yui3 documentation is quite helpful, it can also be beneficial to ask unconventional questions in order to discover the best practices. Are there any gatherings or meetups for all the talented yui developers out there? ...

What is the best way to showcase a PDF file on a webpage with multiple thumbnails using JavaScript or jQuery?

I recently undertook a project at work that involved displaying multiple PDF thumbnails/images on a webpage. These files were dynamically loaded from a directory on my system. Each thumbnail corresponded to a PDF file stored in a different directory. My g ...

E/AndroidRuntime: CRITICAL ERROR: main --- java code in an android app

I've been working on a map application and I've run into some issues. Can anyone help me figure out what's wrong with my code? ERROR 10-25 01:37:41.296 28673-28673/com.onemap.activities E/AndroidRuntime: FATAL EXCEPTION: main 10-25 01:37:4 ...

Unable to transfer information from the Parent component to the Child component

Can you help me solve this strange issue? I am experiencing a problem where I am passing data from a parent component to a child component using a service method that returns data as Observable<DemoModel>. The issue is that when the child component ...

AngularJS allows us to easily include the route provider templateUrl path in the view div, making

I have the following route provider setup: $routeProvider .when('/', { templateUrl: '/slapppoc/Style Library/TAC/Views/tarification/home.html', controller: 'homeController' /* resolve: { // This f ...

Prevent users from navigating back after logging in on a Reactjs application

Is there a way to prevent users from using the browser's back button after redirecting them to another application in ReactJS? In my scenario, I have two applications running simultaneously. Upon successful login, I check the user type. If the conditi ...

Utilize useEffect to dynamically populate several dropdown menus with data

I am currently implementing a method to populate two dropdowns in my component using useEffects. function fetch_data_for_dropdown1() { return axios.get("http://127.0.0.1:5001/dropdownonedata"); } function fetch_data_for_dropdown2() { return axios ...

Locate all posts associated with the specified User ID

Using mongoose, I am able to populate the "Post Schema" with relevant information about users who create the posts. postModule.js const mongoose = require('mongoose'); const postSchema = mongoose.Schema({ title:String, description:String, date ...

Avoid the ability for individuals to interact with the icon embedded within a button

I'm currently working on a website where users need to interact with a button to delete an "Infraction." The button has a basic bootstrap style and includes an icon for the delete action. <button referencedInfraction="<%= i.infractionID %>" ...

How can you create a unique record by appending a number in Javascript?

Currently, when a file already exists, I add a timestamp prefix to the filename to ensure it is unique. However, instead of using timestamps, I would like to use an ordinal suffix or simply append a number to the filename. I am considering adding an incr ...

Using recursive setTimeout in Javascript may not always utilize the entire final JSON object that is returned

My current approach involves making recursive calls to a URL until it returns either a success or reaches the maximum limit of tries. Below is a compact version of the relevant code: function doSomething(numRetries) { $.post('someURL', {retr ...

Is there a way I can detect a browser timeout and display a custom error message?

My webpage in classic asp contains a link to a local IP address, shown below: <a href="http://192.168.1.89">Link</a> When the local IP address is not available, the web browser eventually times out and shows its own error message. I ...

What is preventing me from navigating to other pages in my React application?

Recently, I have been experimenting with ReactJS and encountered an issue where I couldn't access my other pages. The code snippet provided below seems to be the root of the problem. I am in the process of developing a multi-page application using Re ...