$ routeParams未定义。我不知道我改变了什么让它突然变得不起作用

时间:2014-08-17 17:23:17

标签: angularjs angularjs-routing

我不确定这里发生了什么。

 angular.module('myApp', [
        'ngRoute',
        'myApp.controllers',
        'myApp.filters',
        'myApp.services',
        'myApp.directives'
    ]).
        config(function ($routeProvider, $locationProvider) {
            $routeProvider.
                when('/', {
                    templateUrl: '/partials/homepage',
                    controller: 'MyCtrl1'
                }).
                when('/about/:id', {
                    templateUrl: '/partials/'+$routeParams.id,
                    controller: 'MyCtrl1'
                }).
                when('/funnel', {
                    templateUrl: '/partials/funnel',
                    controller: 'MyCtrl2'
                }).
                otherwise({
                    redirectTo: '/'
                });

            $locationProvider.html5Mode(true);
        });

无论我是否浏览/或/ about /:id,我都会得到$ routeParams未定义。

2 个答案:

答案 0 :(得分:3)

您需要注入$routeParams服务才能使用它。但是在您的情况下,您似乎希望根据routeparam动态确定模板。您无法在应用程序的配置阶段直接执行此操作,该应用程序仅作为应用程序初始化阶段的一部分运行一次(并且您也可以在应用程序的配置阶段注入$routeParams,因为没有此类提供程序)。您可能想要查找检索动态模板的方法,并且为了支持此角度,此工具使用函数templateUrl能够根据任何路径参数动态确定模板URL(这将是参数在功能)。

你可以这样做: -

           when('/about/:id', {
                templateUrl: function(routeParam){ //register it as function
                    return '/partials/' + routeParam.id;  //Get the id from the argument
                },
                controller: 'MyCtrl1'
            }).

documentation开始。

  

templateUrl - {string = | function()=} - 返回应由ngView使用的html模板路径的路径或函数。   如果templateUrl是一个函数,它将使用以下参数调用:    {Array.<Object>} - 通过应用当前路线从当前$ location.path()中提取的路线参数

答案 1 :(得分:0)

这是因为这一行:

templateUrl: '/partials/'+$routeParams.id,

您使用$routeParams而不是每次声明或注入它。如果将它添加到您的函数接受的参数中,您的页面应该停止抛出该错误:

config(function ($routeProvider, $routeParams, $locationProvider) {
    // ...
}