Is there a way to manually add route resolve data to a controller without using automatic injection?

Two routes in my application share a controller, but one route requires data to be resolved before the view loads while the other does not.

Here is an example of the routing segments:

...
when('/users', {
    controller: 'UsersCtrl',
    templateUrl: '/partials/users/view.html',
    resolve: {
        resolvedData : ['Accounts', function(Accounts) {
            return Accounts.get();
        }]
    }
}).
when('/users/add', {
    controller: 'UsersCtrl',
    templateUrl: '/partials/users/add.html'
})
...

And here is an example of the controller:

app.controller('UsersCtrl', ['$scope', 'Helper', 'resolvedData', 
    function($scope, Helper, resolvedData) {
        // This works for the first route, but fails for the second route with
        // an unknown "resolvedDataProvider" error
        console.log(resolvedData); 
}]);

Is there a way I can access the resolvedData in the controller without explicitly using the resolve name as a dependency? So that I can perform a check?

Using the $injector doesn't seem to work. I would like to do something like this:

if ($injector.has('resolveData')) { 
     var resolveData = $injector.get('resolveData');
}

However, even this approach doesn't work for the route that has the resolveData set ('/users'):

app.controller('UsersCtrl', ['$scope', 'Helper', '$injector', 
    function($scope, Helper, $injector) {
        // This does not work, it fails with an unknown "resolvedDataProvider" error as well
        $injector.get('resolvedData');
}]);

Is there a way to achieve this in angularjs, or should I just create a new controller?

Thank you.

Answer №1

Just when I thought I hit a dead end, I found another path to follow. The data that was causing the issue is actually stored within the $route object. You can retrieve it like this:

app.controller('UsersCtrl', ['$scope', '$route', 'Helper', 
    function($scope, $route, Helper) {

        if ($route.current.locals.resolvedData) {
            var resolvedData = $route.current.locals.resolvedData;
        }
}]);

Answer №2

If the alternative path does not require it, simply include undefined on that specific route:

router:

when('/users', {
    controller: 'UsersCtrl',
    templateUrl: '/partials/users/view.html',
    resolve: {
        resolvedData : ['Accounts', function(Accounts) {
            return Accounts.get();
        }]
    }
}).
when('/users/add', {
    controller: 'UsersCtrl',
    templateUrl: '/partials/users/add.html',
    resolve: {
       resolvedData: function() {
          return undefined;
       }
    }
})

controller:

app.controller('UsersCtrl', ['$scope', 'Helper', 'resolvedData', 
    function($scope, Helper, resolvedData) {
        if(resolvedData){
          //set some scope stuff for it
        } else {
         //do what you do when there is no resolvedData
        }
}]);

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

Caution when using a React form: Value of `true` has been detected for a non-boolean attribute `validate`

I am trying to address a warning message that I have received index.js:1 Warning: Received true for a non-boolean attribute validate. If you want to write it to the DOM, pass a string instead: validate="true" or validate={value.toString()}. I ...

How to Implement HighCharts in AngularJS Using Json Data

Currently working on learning AngularJS and HighCharts. If you are interested, check out this [Plunker Link][1] I am trying to figure out how to dynamically update the x-axis and bar chart values using data from a JSON object. The y-axis values will remai ...

Tips for enabling multiple v-list-group components to remain open simultaneously (bypassing the default Vue behavior)

Currently, I am facing an issue with Vue's default behavior where only one v-list-group can be open at a time. I am using Vuetify 2.6 and have attempted to use the multiple prop without success. Additionally, individually assigning the :value prop to ...

What methods are available for parsing JSON data into an array using JavaScript?

I possess an item. [Object { id=8, question="وصلت المنافذ الجمركية في...طنة حتّى عام 1970م إلى ", choice1="20 منفذًا", more...}, Object { id=22, question="تأسست مطبعة مزون التي تع... الأ ...

Tips for retrieving the identifier of a row in a mui datagrid when an onClick event occurs

I'm attempting to integrate a material-ui datagrid with a sql database for the purpose of enabling edits to be made via a form rather than editing individual rows and cells one by one. My goal is to pass the row's id as a parameter to a function ...

What are the specific circumstances in which the onerror and ontimeout properties are utilized? (regarding

When utilizing the XMLHttpRequest class to send payload data from a web client to a web server, I encounter some common errors that need to be handled... REQUEST TIMEOUT (CONNECTION TIMEOUT) 500, INTERNAL SERVER ERROR 502, BAD GATEWAY 503, SERVICE UNAVAI ...

Error code -4058 ENOENT indicates that the file or directory does not exist. This issue is usually caused when npm is unable to locate a specific file

Trying to start a react project on my D: drive while having node installed on the C: drive resulted in an error: D:\react> npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path D:\react/package.json npm ERR! errno -4058 npm ERR! ...

What is the best way to locate a document's array item in MongoDB (Mongoose) using its "_id" field?

Here is the schema I'm working with using NestJS and Mongoose: @Schema({ timestamps: true }) export class Listing { @Prop({ type: [{ bidderId: { type: Types.ObjectId, required: true, select: false, ref: User.name, index: true }, ...

What is the best way to implement data loading on scroll in HTML with AngularJS?

I'm working with a HTML Dynamic Table <div class="clearfix reportWrapper" > <div class="reportTable"> <table class="table table-bordered footerBGColor"> <thead fix-head class="headerTable"> ...

Effective ways to conduct Protractor testing on angular-ui-Selectize components

I am exploring how to test a user creation form that includes multiple dropdown controls, specifically angular-ui-select elements. After searching for documentation on selecting items from these dropdowns, I came up empty-handed. This is an excerpt from ...

Is it possible to validate input only during insertion in Objectionjs without validation during updates?

const BaseModel = require("./base_model.js"); class CustomerModel extends BaseModel { static get tableName() { return "customers"; } static get jsonSchema() { return { type: "object", required: ['na ...

Ways to showcase server-side validations for individual input fields in AngularJS and Springboot applications

Is it possible to display errors on top of individual input fields when using an AngularJS service to call a Rest controller? When the response is received from the AngularJS service, it comes as a single error message. This means that all the errors will ...

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Modify the design of the button in the CSS code

I am facing an issue with the layout of the Visible Columns button and unable to standardize it like the buttons above using CSS enter image description here The code snippet for the Visible Columns button is as follows: import React, { useState, useEffe ...

Tips for uploading information and posting it on a different page with mongoDB and Node.js

I am looking to implement a feature on a website where data is submitted to MongoDB from one page, and then retrieved and displayed on another page. The technologies I am working with include node.js, express, Mongoose, and MongoDB. Currently, the data is ...

Make sure to close any existing Featherlight windows before trying to open another one

I'm setting up multiple featherlight instances when the page loads jQuery('.feedback').featherlight(jQuery( "#feedback-box" ), { closeIcon: 'close'}); jQuery('#imprint').featherlight(jQuery( "#imprint-box" ), { closeIcon ...

What is the best way to transfer XML file information using AJAX to a Webmethod?

I'm encountering an issue when attempting to send XML via an ajax call to my Webmethod (C# Webforms): Previously, I successfully tested the ajax call with JSON and was able to send JSON to the Webmethod. Although the response status code returns as ...

injecting a variable from the configuration service into a TypeScript decorator

I am interested in setting up a scheduled task for my NestJs application to run at regular intervals. I found information on how to use intervals in the NestJs documentation. Since my application uses configuration files, I want to keep the interval value ...

`Using top-level await in a module can interfere with the firing of the `onload` event

It seems that the load event is not triggering when I use await for an IndexedDB opening at the top level within an indirectly loaded module. Interestingly, if I remove the await, the load handler works as expected. Similarly, replacing the openDB call wi ...

conducting thorough analysis for detecting modifications akin to $watchCollection in Angular2

I have a situation where I am passing an array of objects from my parent component to child components. Even when a new item is added to the array or the property of an existing object changes, it fails to trigger the ngOnChanges for the affected component ...