Pass $scope and the promise result into the controller constructor by utilizing Angular UI Router

Utilizing angular ui router, I find myself in need of injecting $scope and pre-fetched data into my controller's constructor.

Initially, everything works smoothly when only including the promise in the resolve object. However, as soon as I add the $scope service to the list of injectables, angular ui router fails to resolve the route.

The following is a snippet of working TypeScript code:

$stateProvider.state('parent.child', {
    url: '/child',
    template: 'I am the child state',
    controller: 'TestController',
    controllerAs: 'vm',
    resolve: {                
        viewModel:initializeControllerViewModel
    }
});

initializeControllerViewModel.$inject = [
    '$stateParams',
    '$q',
    '$timeout'
];

function initializeControllerViewModel(
    $stateParams: ng.ui.IStateParamsService,
    $q: ng.IQService,
    $timeout:ng.ITimeoutService)
{
    let deferred = $q.defer();

    $timeout(() =>
    {
        deferred.resolve({
            property1: 'foo'
        });
    }, 500);

    return deferred.promise;    
}

class TestController
{
    constructor(
        viewModel: any)
    {            
        //viewModel should be {property1: 'foo'}
    }
}

Here is the non-functional code:

$stateProvider.state('parent.child', {
    url: '/child',
    template: 'I am the child state',
    controller: 'TestController',
    controllerAs: 'vm',
    resolve: {
        '$scope': '$scope',
        viewModel:initializeControllerViewModel
    }
});

class TestController
{
    constructor(
        $scope: ng.IScope,
        viewModel: any)
    {
        //$scope should be injected
        //viewModel should be {property1: 'foo'}
    }
}

Answer №1

Instead of using scope in ui router, consider utilizing the $inject property within your class

class UpdatedController
{
public static $inject = ['$scope', 'dataModel'];
constructor(
        $scope: ng.IScope,
        dataModel: any)
    {
        //$scope needs to be injected
        //dataModel should have properties like {name: 'John'}
    }
}

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

AngularJS provides the ability to display and conceal table rows with ease

To begin with, I have a requirement to display all rows with the id "main" and hide all rows with the id "review." Next, upon clicking on a "main" row, I want to show a corresponding "review" row below that particular "main" row. Furthermore, if I click ...

The selected check icon does not appear in the console log

Objective: Display preselected data from selected checkbox in console.log Issue: The preselected data is not appearing in the console log. When manually checked, the data shows up. What am I missing? About Me: I am a beginner in Angular. Thank ...

Node.js server experiencing delays handling multiple requests causing timeouts

As someone who is not very experienced with node, I appreciate your patience. I have a node.js server with 2 routes. Throughout the day, both routes receive requests simultaneously. Route 1 runs smoothly, while route 2 is a long-running process that invol ...

Looking for assistance with removing hardcoding in HTML and jQuery?

Currently working on a biography page for my company's website that features a grid layout of the employees' profile pictures. Each picture should be clickable, causing the screen to fade to gray and display an overlay with the respective person& ...

When using NextJS components, they function properly in development mode but encounter issues in production mode

I have encountered a problem with the 'Highlight' component from the 'react-highlight' library while working on a project using NextJS in both development and production modes. During development mode, the component appears as expected ...

Disabling hover effects for mobile devices

I've been searching for a solution to this problem, but nothing seems to work for me. In mobile viewports, I have a dropdown menu with styles applied on :hover, which shouldn't be active due to usability reasons. The structure of the dropdown i ...

Divide a two-dimensional array into square sections and calculate the total of the highest value in each section using Javascript

I am trying to divide a matrix into square regions of specified dimensions (k) starting from the upper left corner and then calculate the sum of the maximum value in each region. Here is my progress so far. arr = [ [ 0, 8, 1, 1, 10, 6 ], [ 6, 8, 7, ...

Capybara's attach_file function is not properly activating the React onChange handler in Firefox

Currently, I am conducting tests on the file upload feature of a React-built page. The page includes a hidden file input field with an onChange event listener attached to it. Upon selecting a file, the onChange event is triggered and the file is processed ...

Leveraging various techniques within a single controller in AngularJS

I am seeking assistance and advice on a coding issue I am facing. I am attempting to use two methods in one controller. The first method is to display selected rooms, while the second method is to display selected pax. However, only the first method seems ...

Error encountered when rendering an external link through a React component script

Here is the code for my component: import React, { Component } from 'react'; export default class Porfolio extends Component { render() { let resumeData = this.props.resumeData; return ( <section id="portfolio" ...

encountering difficulties with installing dependencies using yarn or npm

After cloning a repository, I attempted to install the dependencies using npm install or yarn but encountered the following errors: For Yarn: https://gyazo.com/2fdf52c4956df2e565cc0b1cedf24628 For npm install: https://gyazo.com/a1d197e9ead89dbe4a7d3c5b8f ...

Issue: React child must be a valid object - Runtime Error Detected

As I delve into the world of React, NextJs, and TypeScript, I stumbled upon a tutorial on creating a navbar inspired by the 'Strip' style menu. It has been quite a learning journey for me as a newbie in these technologies. After seeking help for ...

Having trouble with my browser freezing whenever I use PhoneGap in conjunction with jQuery Mobile

While developing my phoneGap app with jQuery Mobile integration, I encountered some issues. Before importing jQuery Mobile, my page was running normally. However, upon importing jQuery Mobile and running index.html, I started getting unexpected popups. Af ...

What is the process for finding the total of numerous arrays?

I need help solving an equation that involves adding numbers from a list of randomly generated arrays, following the indices. Each array in the list consists of four fixed-length random numbers: const list = [ [2, 9, 1, 2], [2, 3, 9, 4], [4, 7, 8, ...

What is the process for designing bootstrap labels similar to this style?

https://i.sstatic.net/A0nUt.png I am looking to create an input design that changes based on the user's action. When the label is clicked, a violet line should appear. If the input is successful, a green line appears below the label. And for errors, ...

Using Vuetify to display text fields in a single row

Check out this Vue component template (View it on CODEPEN): <div class="some-class"> <v-form > <v-container @click="someMethod()"> <v-row> <v-col cols="3" sm="3" v-for="p in placeholders" ...

What is the process for creating a wait condition specifically for browser.title()?

Can someone assist me with finding a way to wait for the browser title? I'm currently using browser.getTitle() but my script is timing out. Unfortunately, I cannot use browser.sleep in this situation. Is there a way to achieve this using browser.wait( ...

JavaScript guide: Deleting query string arrays from a URL

Currently facing an issue when trying to remove query string arrays from the URL. The URL in question looks like this - In Chrome, it appears as follows - Var url = "http://mywebsite.com/innovation?agenda%5B%5D=4995&agenda%5B%5D=4993#ideaResult"; ...

The stacking order of elements is not affected by the z-index property when using absolute positioning

I have developed a unique custom toggle switch component with the following structure: <template> <div> <label class="switch"> <input type="checkbox" :checked="value" @c ...

Using AJAX to manipulate the document structure and execute a function

Currently, I am operating on Linux -both browser side & server side- using either Firefox 38 or 42. For more context, you can refer to this question and the GitHub project containing my GPLv3 code. The web application is not standard as it typically has on ...