【问题标题】:In Angular, how to find the route that "called" the controller from inside the controller?在 Angular 中,如何从控制器内部找到“调用”控制器的路由?
【发布时间】:2023-03-25 03:45:01
【问题描述】:

我知道两个或多个路由可以共享同一个控制器。但是,在控制器上,我想知道哪个路由“调用”它。为什么?哪条路由将决定我是加载记录列表、通过其 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).
     */
});

除非有一些技巧可以从路由配置中提取,比如使用解析,以某种方式?

【问题讨论】:

  • 我查看了 resolve,似乎它会过多地占用配置部分。我想解决作为函数的“属性”确实成为控制器中的依赖项。我想这是维护的问题。

标签: angularjs model-view-controller controller angularjs-routing


【解决方案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` ...       

});

演示

http://plnkr.co/edit/SoRmRFl7gJMxmJ9bXzgS?p=preview

【讨论】:

  • 询问前任控制器的问题。我也在寻找这个解决方案。
【解决方案2】:

导入 $locationProvider 并在控制器中检查 $location.path()

if($location.path() == '/record")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 2017-02-10
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多