Trouble fetching data for my controller in AngularJS using UI Router resolve

My attempts to inject a resolve object containing loaded data into my controller are resulting in an Unknown Provider error :

Error message: Unknown provider: configServiceProvider <- configService

Below is the code I am working with:

StateProvider

$stateProvider
    .state('index', {
        abstract: true,
        url: "/index",
        templateUrl: "#",
        resolve: {                
            configService: function () {
                return {
                    "helloText": "Welcome in Test Panel"
                };
            }
        }
    })

Controller

function MainCtrl($scope, configService) {
    $scope.config = configService;
};

angular.module('dot', ['ui.router'])
    .config(config)
    .controller('MainCtrl', MainCtrl)

Snippet

function config($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise("#");

  $stateProvider
    .state('index', {
      abstract: true,
      url: "/index",
      templateUrl: "#",
      resolve: {
        configService: function() {
          return {
            "helloText": "Welcome in Test Panel"
          };
        }
      }
    })
};

function MainCtrl($scope, configService) {
  $scope.config = configService;
};

(function() {
  angular.module('dot', [
      'ui.router', // Routing
    ])
    .config(config)
    .run(function($rootScope, $state) {
      $rootScope.$state = $state;
    })
    .controller('MainCtrl', MainCtrl)
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.13/angular-ui-router.min.js"></script>
<div ng-app="dot">
  <div ng-controller="MainCtrl as main">
    <div ui-view>
    </div>
  </div>
</div>

I seem to be encountering issues due to defining my resolve object after the controller has already loaded. As someone new to angularJS, any guidance on resolving this issue would be greatly appreciated.

Thank you.

Answer №1

It seems that the usage of ng-controller and UI-Router state resolve might not work well together, causing issues with injecting "MainCtrl" from the "another-world" into UI-Router's resolve/service.

However, there is a workaround solution by converting it into a new state:

// Introducing a new root state to handle root (index.html) content
// without affecting URL or state names
.state('root', {
    abstract: true,
    template: '<div ui-view=""></div>', // placeholder for child states
    resolve: {                
        configService: function () {    // available for any state within hierarchy
            return {
                "helloText": "Welcome in Test Panel"
            }
        }
    },
    // Adding 'MainCtrl' as part of UI-Router
    controller: 'MainCtrl'
})

The existing root state 'index' will now be nested under a real, yet abstract state called 'root', decoupling it from actual URLs.

// Updated state for index
.state('index', {    // injected into parent template
    parent: 'root',
    abstract: true,
    url: "/index",
    templateUrl: ...,
    // No need for additional resolve since it's already handled in root state
    //resolve: { }
})

Adjustments to index.html

<div ng-app="dot">
  <div ui-view="></div> // here will load the root state with 'MainCtrl'
  //<div ng-controller="MainCtrl as main">
  //  <div ui-view>
  //  </div>
  //</div>

</div>

You may also want to review - Nested states or views for layout with leftbar in ui-router?

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

Deno -> What steps should I take to ensure my codes run smoothly without any errors?

Trying to import locally Experimenting with Deno v1.6.0 in a testing environment Attempting local imports using Deno language Local directory structure: . └── src └── sample ├── hello_world.ts ├── httpRequest. ...

Disable object rotation when hovering the mouse over it in three.js

I've created a function to prevent the rotation of a three.js object when the mouse hovers over it. function onDocumentMouseUp( event ) { event.preventDefault(); mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = - ( event.clientY / w ...

Issue with Vue JS: e.preventDefault not functioning correctly when using Axios

I am facing an issue in my Laravel project where I have implemented a method in the Vue instance to validate resource availability upon form submission. The validation is done through an AJAX call using axios, and if any resources are unavailable, I receiv ...

Tips for managing Ajax JSON response in a PhoneGap application

Although there are a few posts on this topic, I am struggling to piece together the necessary components to make it work. I am in the process of converting a web application into an app using phonegap and I am attempting to create a search form that retri ...

How can I specify the exact width for Bootstrap 3 Progress Bars?

I have a single page that displays all my files in a table format, and I also have the count of open and closed files. My goal is to represent the percentage of closed files using a progress bar. The width of the progress bar should change based on this p ...

How can I use Express.js to send an image file instead of a binary file?

When dealing with a React request in express, I am encountering an issue where I receive the image binary file instead of the actual image file as a response. I have attempted using methods such as res.sendFile and res.download to send the image, but they ...

How can I resize and horizontally align an image using html/css?

Is it possible to resize, crop and center an image using only HTML/CSS? (Using the img tag or CSS sprite) For instance, if I have a 500x500 pixel image, I would like to resize it to a 250x250 pixel image To make the actual visible image 100x100 pixe ...

Using the concept of method chaining in JavaScript, you can easily add multiple methods from

Hey there! I'm looking for some assistance with dynamically building a method chain. It seems like it should be pretty straightforward if you're familiar with how to do it... Currently, I am using mongoose and node.js to query a mongo database. ...

Fill Dropdown 2 according to the choice made in Dropdown 1

I have successfully populated 2 dropdowns directly from the database. However, I am facing an issue where the values in the second dropdown need to be based on the selection made in the first dropdown. Being new to Angular, I am struggling to figure this o ...

What seems to be the issue with the data initialization function not functioning properly within this Vue component?

In my Vue 3 component, the script code is as follows: <script> /* eslint-disable */ export default { name: "BarExample", data: dataInitialisation, methods: { updateChart, } }; function dataInitialisation() { return { c ...

What is the process of generating a row in AngularJS?

I am struggling to create a row as shown in the image. Currently, my circle is not positioned on the right side and my "P" element is not receiving the background color. Here is the code snippet: http://plnkr.co/edit/qIz2rFgW8n3J92evCRTd?p=preview Is it p ...

Utilizing async await in a JavaScript event: A guide

I have coded the introduction page for my game, which includes a submit button and a textbox for users to input their username. Upon pressing the submit button, the code posts the name into a JSON file and retrieves all the data from the JSON file to sen ...

Filling out the form will automatically direct you to the text input section

I'm trying to figure out if I can create an input box in HTML that directs the user to a specific HTML file based on the word they enter. For example, if they type "Doctor", it would redirect them to the page doctor.html. This is for a school project ...

Can you explain the purpose of the .json() function in Angular2?

Can you explain the purpose of the .json() function within http requests in Angular2? Here is an example code snippet: this.http.get('http://localhost:8080/getName') .subscribe(res => this.names = res.json()); Is it correct to assume that t ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

Encountering an issue following the installation and integration of an npm module within a Meteor

I recently started a project using the latest version of Meteor. I added a new package by running the command: meteor npm install --save name_of_package Since this package is meant for the client side, I created a file called mypackage.js inside the /cli ...

Incorporating stick-to-top scroll functionality using AngularJS and ng

I am trying to implement a 'sticky' scroll on dynamic content. My current working example can be found here. It seems to be working, but I encounter a small 'flicker' when new items are appended. This issue seems to be related to the se ...

sliding effect of the background image

Currently, I am in the process of creating a navigation system that includes a background image slide effect. My goal is to mimic the design of a specific website: http://tympanus.net/Tutorials/BeautifulBackgroundImageNavigation/ However, my challenge lie ...

How come my RXJS next method is being invoked before the $digest cycle is completed, and what is the best way to wait for it to

Below is a code snippet written in Coffeescript: beforeEach "We should see the list changed event", (done) -> constructorSubscription = importList.onListChanged().subscribe -> # Expects constructorSubscription.unsubscribe() ...

Sending basic HTML from Express.jsSending simple HTML content from an Express.js

Within my index.html document, I have the following: <input name='qwe'> {{qwe}} I am looking to send {{qwe}} in its literal form, without it being replaced by server-populated variables. How can I achieve this? My initial thought was to ...