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

Is there a way to manipulate a website's HTML on my local machine using code?

I am currently working on a project to create a program that can scan through a website and censor inappropriate language. While I have been able to manually edit the text using Chrome Dev tools, I am unsure of how to automate this process with code. I ha ...

Develop a new object using NodeJS within a module for a function

I am working with a file named item.js exports.itemParam = function(name, price, url, id){ this.name = name; this.price = price; this.id = id; this.url = url; }; In my www.js file, I have imported item.js like this: var item = require('../m ...

Sending a parameter to a confidential npm module

I've developed a custom npm module that can be used in my applications by including this code snippet in the HTML: <app-header-name></app-header-name> Here is the TypeScript code inside the npm package: import { Component, OnInit } from & ...

Utilizing Boolean Operators in JavaScript with Thymeleaf: A Guide

When incorporating Boolean conditions in JavaScript with Thymeleaf using th:inline="javascript", an exception is thrown which appears as follows: org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 22; The entity name must immediately follow the ...

The upcoming development does not involve creating an entire HTML webpage using on-demand static site generation (SS

Iā€™m encountering a problem when utilizing getStaticPaths and getStaticProps to create an on-demand SSG for a sharing page. My setup involves Next v12.1.0 and React 17.0.2. After building a specific /[id] page, I can retrieve the data but the HTML output ...

Angular Transclude - ng-repeat fails to iterate over elements

Recently, I've been experimenting with Angular directives and encountered a peculiar issue... Check out the code snippet below: <!DOCTYPE html> <html> <head> <title>Directive test</title> <script type="text/ja ...

Unable to retrieve the width of an `element` using Angular's built-in jQuery method

I'm attempting to retrieve the width of an element using the AngularJS link method, but I'm not seeing the expected result. Here's my code: var myApp = angular.module("myApp", ['ngResource']); myApp.factory("server", function($r ...

Separate the elements with a delimiter

I am in the process of inserting various links into a division by iterating through a group of other elements. The script appears to be as follows $('.js-section').children().each(function() { var initial = $(this).data('initial'); ...

Determining the specific condition that failed in a series of condition checks within a TypeScript script

I am currently trying to determine which specific condition has failed in a set of multiple conditions. If one does fail, I want to identify it. What would be the best solution for achieving this? Here is the code snippet that I am using: const multiCondi ...

Struggling with certain aspects while learning Nodejs and ES6 technologies

Below is an example of using the ES6 method.call() method that is causing an error var obj = { name: "Hello ES6 call", greet: function(somedata) { this.somedata = somedata console.log(this.somedata) ...

Jasmine: A service in Angular for testing that replaces console.log

I have developed an Angular logging service that replaces console.log and other methods based on an environment constant. Here's a simplified example: if(!DEBUG_ENV) { console.log = function(){}; } Now, my query is how can I use Jasmine to vali ...

Identifying the HTML elements beneath the mouse pointer

Does anyone know the method to retrieve the HTML tag located directly under the mouse cursor on a webpage? I am currently developing a new WYSIWYG editor and would like to incorporate genuine drag and drop functionalities (rather than the common insert at ...

Working with Ruby on Rails by editing a section of embedded Ruby code in a .js.erb file

Currently, I am in the process of developing a single-page website and have successfully implemented ajax loading of templates to insert into the main content section. However, I am encountering difficulties when trying to do this with multiple templates u ...

What is the best way to display the weather information for specific coordinates in ReactJS?

I've been working on a code that retrieves farm details based on longitude and latitude. My goal now is to fetch the weather information for that specific farm using openweathermap However, each time I attempt to do so, an error message {cod: '4 ...

What are some strategies for creating a recursive function in JavaScript that avoids exceeding the maximum call stack size error?

I need assistance creating a walking robot function in JavaScript, but I am encountering a call stack size error. function walk(meter) { if(meter < 0) { count = 0; } else if(meter <= 2) { count = meter; ...

Unexpected behavior: getElementById returning URL instead of element

I created a function that accepts a thumbnail path as an argument, waits for the bootstrap modal to open, and then assigns the correct path to the thumbnail href attribute within the modal. However, when I use console.log with the element(el), it displays ...

Verify the identity of all REST API requests without the need for a username or password in order to obtain a

I have a unique setup where I am selling products. The API fetches product data from a centralized node back-end and displays it on an angular front-end that is hosted on multiple domains. The challenge I'm facing is the need to authenticate all reque ...

Passing the unique identifier of a record in NextJS to a function that triggers a modal display

I'm currently facing an issue with my NextJS component that displays a list of people. I have implemented a delete button which triggers a modal to confirm the deletion of a person, but I am struggling with passing the id of the person to be deleted. ...

What is the best way to set up jest to generate coverage reports for Selenium tests?

I recently made the switch to using jest for testing my JavaScript project after encountering coverage issues with mocha and chai. While my unit tests are providing coverage data, my Selenium tests are not. I've tried various solutions found in outdat ...

Having trouble resolving errors encountered while running the `npm run build` command, not sure of the steps to rectify

I am currently working on my first app and attempting to deploy it for the first time. However, I have encountered an error that I am unsure of how to resolve. When running "npm run build", I receive the following: PS C:\Users\julyj\Desktop& ...