我知道两条或更多条路线可以共享同一个控制器。但是,在控制器上,我想知道哪条路线“叫”了它。为什么?哪条路由将决定我是否会加载记录列表,按其ID加载一条记录,或者根本不加载任何内容。
我有以下路线配置:
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: "/"
});
});
我只想使用一个控制器,所以我有一个:
angular.module("app").controller("RecordsController", function($http, $routeParams){
/* I know that if $routeParams.id exists, it's 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).
*/
});
除非有一些技巧可以从路由配置中提取,比如解决方法,不知何故?
答案 0 :(得分:1)
$location.path()
来自docs:
$ location服务解析浏览器地址栏中的URL(基于 在window.location上)并使URL可用于您的应用程序。
...
Getter和setter方法
// get the current path $location.path();
angular.module("app").controller("RecordsController", function($http, $routeParams, $location){
var path = $location.path();
// Do something with `path` ...
});
答案 1 :(得分:1)
导入$ locationProvider并在控制器中检查$ location.path()
if($ location.path()==' / record")