【问题标题】:Angular $routeParams empty objectAngular $routeParams 空对象
【发布时间】:2015-09-10 15:45:05
【问题描述】:

我正在尝试使用 Angular 的 routeParams 从我的 url 获取查询值。

我在我的 html 页面中包含了 angular-route:

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.min.js"></script>

在我的应用中包含 Ng-Route:

var app = angular.module('app', [
    'ngRoute',
    'reportController'
]);

并将我的控制器设置如下:

var reportController = angular.module('reportController', []);
reportController.controller('CandidateCtrl', ['$scope', '$routeParams',
        function($scope, $routeParams) {
    console.log(JSON.stringify($routeParams, null, 4));
    $scope.person = $routeParams.person;
}]);

但是,当我访问以下 URL 时,routeParams 是一个空对象:{}。

http://localhost:8080/report?person=afe75cc7-fa61-41b3-871d-119691cbe5ad

我做错了什么?

编辑:

我已经配置了可能的路线 - 我的 routeParams 对象仍然为空。我试过了:

famaApp.config(['$routeProvider', function($routeProvider) {
           $routeProvider.
            when('/report:person', {templateUrl: 'Report.html', controller: 'CandidateCtrl'});
}]);

when('/report?person', {templateUrl: 'Report.html', controller: 'CandidateCtrl'});

【问题讨论】:

  • 您必须配置对该路由有效的参数。
  • 正如有人已经说过的,您需要首先配置您的路由和参数才能获取它们。可能与此重复 stackoverflow.com/a/22718007/138624

标签: javascript angularjs ngroute


【解决方案1】:

【讨论】:

    【解决方案2】:

    你必须设置你的路由来接收你想要的参数 $routeProvider..

    例子:

    app.config(['$routeProvider', '$locationProvider' function ($routeProvider, $locationProvider) {
    
        $routeProvider
            .when('/',
            {
                templateUrl: 'someHtmlUrl',
                controller: 'someController',
                controllerAs: 'someCtrl',
                caseInsensitiveMatch: true
            })
            .when('/:person',
            {
                templateUrl: 'someHtmlUrl',
                controller: 'someController',
                controllerAs: 'someCtrl',
                caseInsensitiveMatch: true
            })
            .otherwise(
            {
                templateUrl: 'someHtmlUrl'
            });
        $locationProvider.html5Mode(true); //Use html5Mode so your angular routes don't have #/route
    }]);
    

    那你就可以了

    http://localhost:8080/afe75cc7-fa61-41b3-871d-119691cbe5a
    

    $routeProvider 会调用你的 html 和你的控制器,就像你在 .when('/:person'.. 看到的那样.人。

    【讨论】:

    • 如果使用$locationProvider.html5Mode,你需要在你的索引中有一个,除非指定了$locationProvider.html5Mode({ enabled: true, requireBase: false });
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2016-02-07
    • 2016-05-10
    • 2023-03-14
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    相关资源
    最近更新 更多