In Angular, how do I find the route that the controller has "called" from within the controller?
I know that the same controller can be used for two or more routes. However, from the dispatcher, I would like to know which route "called" it. What for? Which route will determine whether I will load a list of records, load a single record by its ID, or not load anything at all.
I have the following route configuration:
angular.module("app").config(function ($routeProvider) {
$routeProvider.when("/", {
templateUrl: "home.html"
}).when("/records", {
templateUrl: "records.html",
controller: "RecordsController"
}).when("/record/create", {
templateUrl: "editRecord.html",
controller: "RecordsController"
}).when("/template/edit/:id", {
templateUrl: "editRecord.html",
controller: "RecordsController"
}).otherwise({
redirectTo: "/"
});
});
I only want to use one controller, so I have one:
angular.module("app").controller("RecordsController", function($http, $routeParams){
/* I know that if $routeParams.id exists, it probably the
/record/edit/:id route. But if $routeParams.id is null/undefined,
I don't know which of /records or /record/create "called"
this controller. I would like to know which route so I can
decide to load a list (if /records) or not (for /record/create).
*/
});
If there are any tricks to pull out of the route config, as with permission, somehow?
+3
source to share
2 answers
Use $location.path()
from the docs :
The $ location service parses the URL in the browser's address bar (based on window.location) and makes the URL available to your application.
...
Getter and setter methods
// get the current path $location.path();
For use in a controller
angular.module("app").controller("RecordsController", function($http, $routeParams, $location){
var path = $location.path();
// Do something with `path` ...
});
Demo
+1
source to share