Top spot for locating resolve functions in AngularJS

I'm currently in the process of setting up resolves for my admin panel routes and I'm pondering the best way to store them without cluttering my router with methods. Here's what I have so far:

when('/admin', {
    templateUrl: 'app/private/admin/view.html',
    controller: 'admin',
    resolve: ['$q', '$location', 'api', function($q, $location, api){

        var deferred = $q.defer(),
            session = api.session();

        if(session){
            deferred.resolve(session); 
        } else {
            api.authorise().success(function(response){
                deferred.resolve(response); 
            }).error(function(error){
                $location.path('/login');
                deferred.reject(error);
            });
        }

        return deferred.promise;

    }]
})

I believe a more organized approach would be to keep the resolves within the controller used for that route, like this:

when('/admin', {
    templateUrl: 'app/private/admin/view.html',
    controller: 'admin',
    resolve: adminCtrl.resolve
})

Unfortunately, the admin controller is not directly accessible from the configuration, meaning I might need to use a provider which could lead to a messy codebase as the application grows.

How do you manage your resolves? Is there a way to store them directly in the controller itself?

Answer №1

My usual approach is to rely on services to address the issues I need resolved:

when('/admin', {
templateUrl: 'app/private/admin/view.html',
controller: 'admin',
resolve: { adminData: function(myService) { return myService.list(); } }
});

Advanced angular routers like UI-router offer the ability for states to inherit from parent-states. To apply a resolve across multiple states, inheritance can be used by defining the resolve in the parent-state. (Refer to https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views).

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

Mistakes in my async/await workflow: How am I incorrectly loading and injecting this external script?

Encountering a simple problem: some calls to refresh() cause window.grecaptcha to become undefined. It doesn't happen all the time, probably due to network delays. Debugging this issue is proving to be tricky, especially since I'm still new to th ...

Using JavaScript to place markers on a Google Map may encounter an issue with a for

Close to solving a three-day challenge. Currently working on placing markers on a Google Map using latitudes and longitudes stored in a Django model. This is my first time using AJAX, but I'm giving it a shot to make this work. Firebug is pointing out ...

AngularJS and synchronized queueing of API requests

I am attempting to develop a synchronized queue for API requests using AngularJS. class x { public y() { ... restRequest(); } } I have this class, along with a whiteboard canvas. When I drop an entity onto the canvas, the method &a ...

Despite returning an "OK" status, the jQuery Ajax Codebehind Post fails to function properly

Attempting to call a function in ASP.NET with jQuery Ajax: var params = "{'name':" + "\"" + name + "\"}"; $.ajax({ type: "POST", url: "CreateTopic.aspx/CreateNewTopic", data: params, ...

The radio button in the HTML form is disabled when the user selects

I have two radio buttons labeled Billable "Y" and Billable "N". These radio buttons are linked to a database with corresponding values of "Y" or "N". If the user selects "Y" using the radio button, then the NonBillableReason text box should be disabled. ...

Is there a way to switch (transpose) the rows and columns of a dynamically generated HTML table from Highchair in Angular 12?

Click here to view the code for creating a highchart table. In the provided example, I have successfully implemented a highchart table using the code below. Highcharts.chart('container', { title: { text: 'Solar Employment Growth by Sec ...

Ways to implement collapsible functionality into table rows

I have a table on my website and I want to initially display only 3 rows. When the user clicks on the 'more' button, I want the rest of the rows to be displayed. However, when I tried implementing this with code, I encountered rendering issues. I ...

What is the best way to use selenium for iterating through multiple pages on a website?

Recently, I've been attempting to create a Python script to scrape a specific website for a list of all URLs. The website in question is . The main challenge I've encountered is that the website utilizes Javascript for navigation, making it diff ...

The Selenium driver's execute_script() function is not functioning as expected

When I attempt to execute a JavaScript using driver.execute_script, nothing happens and the system just moves on to the next line of Python code. Any ideas? I've been web scraping on a webpage, using JavaScript in the Console to extract data. The Jav ...

Utilizing an Application Programming Interface in React Native

Recently diving into React Native, I embarked on creating a basic app leveraging the Marvel API along with an API wrapper. My aim is to implement an infinite scroll view using VirtualizedList. Here's where I could use some guidance: What should be pas ...

Prevent the mouseup event in jQuery when the mouse has previously been moved

I have a div with a row of span buttons displayed horizontally. Since there are too many buttons to fit on the screen, I want to enable the user to click and drag the entire row of buttons. However, my challenge is to ensure that the button's mouseup ...

Vue search button not returning results

Hello, this is my HTML file. <div id="app1" v-cloak> <input v-model="term" type="search"> <button @click="search">Search</button> <p/> <div v-for="post in posts" class="post"> ...

Disable checkboxes upon page initialization

I am working with a form that includes checkboxes. Whenever the page loads, clicking on the checkboxes automatically checks them. However, I am looking for a solution where the checkboxes are disabled or not clickable during the page load process. Once th ...

What is happening with the arrangement of $scope in Angular 1.x?

In my controller, I am loading content using ajax and want a spinner to appear while it's loading. The code snippet is as follows: <i class="fa fa-2x fa-spin fa-spinner" ng-show="isLoadingContent"></i> Accompanied by the following JavaSc ...

Only validate the nested object if the parent object is already present

In my scenario, I have a request body structured as follows: { "folder": { "value": "testFolder", "operator": "=" }, "name": { "value": "5456", "operator": "contains" } } While the presence of the request body is optional, I want to ensure that b ...

The deep reactivity feature in Vue3 is functioning well, however, an error is being

I am currently using the composition API to fetch data from Firestore. While the render view is working fine, I am encountering some errors in the console and facing issues with Vue Router functionality. This might be due to deep reactivity in Vue. Here is ...

How do Angular 1.X controllers and directives interact with each other?

I want to understand how directives and controllers collaborate when they are both present in a component, instead of just knowing the difference between them. ...

I am looking for JavaScript or jQuery code that allows me to incorporate a "Save This Page As" button

Is there a way to enhance the saving process for users visiting an HTML page, rather than requiring them to go through File > Save As? I am interested in implementing a "Save Page As" button on the page that would trigger the save as dialog when clicke ...

What is the best way to save information to a JSON file using AngularJS?

If I have an HttpService implemented in a controller that returns JSON data, what is the best way to save this data to a file on my disk? My goal is to save this result as a mock file so I can use it offline instead of relying on the online service. ...

Creating a transcluding element directive in AngularJS that retains attribute directives and allows for the addition of new ones

I've been grappling with this problem for the past two days. It seems like it should have a simpler solution. Issue Description The objective is to develop a directive that can be used in the following manner: <my-directive ng-something="somethi ...