$routeProvider - providing controller dependencies based on the URL path

Take a look at the following code snippet:

var app = angular.module("app", [], function($routeProvider) {
  $routeProvider
    .when("/page1", { controller: "MyController" })
    .when("/page2", { controller: "MyController" })
    .when("/page3", { controller: "MyController" });
});

app.factory("StrategyOne", function() {...});
app.factory("StrategyTwo", function() {...});
app.factory("StrategyThree", function() {...});

app.controller("MyController", function(Strategy, $scope) {...});

If you want to inject either StrategyOne, StrategyTwo, or StrategyThree into MyController based on the URL, you can consider something like this pseudo-code:

var app = angular.module("app", [], function($routeProvider) {
  $routeProvider
    .when("/page1", { controller: "MyController", Strategy: "StrategyOne" })
    .when("/page2", { controller: "MyController", Strategy: "StrategyTwo" })
    .when("/page3", { controller: "MyController", Strategy: "StrategyThree" });
});

Is there any way to achieve this functionality using AngularJS?

Answer №1

Absolutely! AngularJS has a neat solution for handling this using the resolve property within a route definition. You can learn more about it here.

In essence, you could implement something like:

var app = angular.module("app", [], function($routeProvider) {
  $routeProvider
    .when("/page1", { controller: "MyController", resolve: {Strategy: "StrategyOne"}})
    .when("/page2", { controller: "MyController", resolve: {Strategy: "StrategyTwo"}})
    .when("/page3", { controller: "MyController", resolve: {Strategy: "StrategyThree"}});
});

This enables you to effortlessly inject the appropriate strategy into your controller. AngularJS dependency injection at its finest!

If you're interested in diving deeper into the concept of resolve, there's an informative video tutorial available at: http://www.youtube.com/watch?v=P6KITGRQujQ&list=UUKW92i7iQFuNILqQOUOCrFw&index=4&feature=plcp

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

An insightful guide on effectively binding form controls in Angular using reactive forms, exploring the nuances of formControlName and ngModel

Here is the code snippet: list.component.html <form nz-form [formGroup]="taskFormGroup" (submit)="saveFormData()"> <div nz-row *ngFor="let remark of checklist> <div nz-col nzXXl="12" *ngFor="let task of remark.tasks" styl ...

The specified timeout elapsed without the jasmine async callback being invoked

Having recently ventured into Protractor and javascript, I've encountered a persistent error that none of the existing solutions seem to shed light on. The issue revolves around understanding async callbacks within my Page Object model implementation. ...

The controller method appears to be unable to detect any parameters

I have been trying to pass an ID in the URL but my controller is not receiving that value. $("#ChangeSlideForm").on("submit", function(){ $.ajax({ type: "POST", url: base_url + "Visualiser/ChangeSlide/21", su ...

Should property paths be shortened by utilizing new variables for better organization?

Yesterday, someone asked me why I would introduce a variable to shorten the property path. My answer was simply that it feels easier to read. Now I am curious if there are any objective reasons to choose between the two options listed below (such as memory ...

What is the method for accessing an image in JavaScript?

Currently, I am developing a currency converter for a gaming marketplace and I would like the users to be able to generate images using JavaScript. While most of the work is completed, I am facing an issue where the images are not displaying properly and i ...

Experimenting with d3 using Node.js, JSDOM, and Jasmine

I am new to Javascript and node.js, and I want to test if a basic bar chart is being rendered in my node.js/d3 application using jasmine. Could someone provide guidance on what steps I need to take? test.js (file that needs testing): var d3 = require(&ap ...

Error message "SyntaxError: Unexpected token < in JSON at position 0" encountered while using AJAX

When data is sent through an ajax request and processed, a returned array is encoded into json format. $response = array( 'data' => $leaveData, 'message' => 'Event added successfully', ...

Angular UI Router Uib Modal: Refresh the page below when clicking outside the modal

I am currently using angular-ui-router-uib-modal and have a query regarding it. After closing my modal (which confirms a successful/failed operation), I want to reload the page below that displays a list of data. In the example provided, I can define thi ...

Showcasing the selected menu item's value on an Angular button

I've encountered an issue where I have a list of menu items: <md-menu-item ng-value="menuItem.value" ng-repeat="menuItem in filtermenu.menuItems" ng-click="activeFilterCtrl.selectedfilter(menuItem)" translate> <md-button> {{ m ...

How to eliminate ampersands from a string using jQuery or JavaScript

I'm having trouble with a seemingly simple task that I can't seem to find any help for online. My CSS class names include ampersands in them (due to the system I'm using), and I need to remove these using jQuery. For example, I want to chan ...

Utilizing Django to determine the appropriate view based on whether it is a GET request or an AJAX POST method

In my Django project, I have a view that serves different purposes depending on whether the request method is GET or POST. When it's a GET request, the view simply renders the page for the user. On the other hand, when it's a POST request, I use ...

What is the best way to incorporate a generated ID into the datepicker() function whenever a button is clicked?

I'm looking to dynamically generate a row of input fields with unique IDs every time the "add another flight" button is clicked, similar to the functionality seen on destina.us. Additionally, I need to incorporate these generated IDs into the jQuery U ...

Testing the NestJS service with a real database comparison

I'm looking to test my Nest service using a real database, rather than just a mock object. While I understand that most unit tests should use mocks, there are times when testing against the actual database is more appropriate. After scouring through ...

What is the best way to halt an animatePNG sequence?

I found a library that allows me to animate PNG images, you can check it out here: https://github.com/pixelmatrix/animatePNG After looking at the source code, I noticed there is a stop() method available. Can someone guide me on how to call this method in ...

An error message stating "ReferenceError: str is not defined" was encountered in Firefox while using the Gettext Library

The gettext.js library seems to be giving me trouble. When I try to run the "index.html" file, an error message saying "ReferenceError: str is not defined" pops up. this.LCmessages[lang] = new jsGettext.Parse(str); I'm not sure where the str variabl ...

Combining Import and Require in a Node JS File

Having some trouble with the normalize-url package. It needs to be imported instead of required since it's not supported in ES module. I tried to work around this by adding some code I found online, but it doesn't seem to be fixing the issue for ...

Here are some tips for retrieving information from a JavaScript object

My goal is to extract the values of free_time, done_ratio, criticalTask, and dependency from a JavaScript object for each task. I attempted to achieve this, but unfortunately, it didn't yield the desired results. var mock_data_allocation = {"alloc ...

Empty value for $_POST variable following xmlhttp request

When my code makes an xmlhttp request to a php file with an ID for record deletion from the database, I encounter an issue. The error message 'comicID' is undefined shows up when attempting to delete. This signifies that the variable containing t ...

Choosing an option in react-select causes the page to unexpectedly shift

Encountering a problem with a mobile modal developed using react-select. The selectors are within a div with fixed height and overflow-y: scroll. Upon selecting an option for the 'Choose observer' select, the entire modal briefly jumps down in th ...

How to implement dynamic aggregate functions with parameters in Express and Mongoose

I have implemented an aggregate function in mongoose to fetch some data, with a static implementation. app.get("/male",function (req,res) { Record.aggregate([ { $match: {"gender": "male"} }, { $group:{ _i ...