如何在AngularJS中获取url参数

时间:2014-05-26 23:57:01

标签: javascript angularjs

知道为什么$routeParams正在记录undefined?我希望它能记录一个id。

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

app.config([
  '$routeProvider', function($routeProvider) {
    return $routeProvider.when('/entries/:entryId', {
      controller: 'EntryController'
    });
  }
]);

app.controller('EntryController', [
  '$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {
    $http.get("/entries/" + $routeParams.entryId + ".json").success(function(data) {
      return $scope.phone = data;
    });
    // This logs undefined.
    console.log($routeParams.entryId);
  }
]);

当前网址为http://localhost:3000/entries/5383a2f44d6f6816d7020000

1 个答案:

答案 0 :(得分:1)

我的路线配置中没有使用return而我在示例中找不到templateUrl

$routeProvider.when('/entries/:entryId', {
      templateUrl: 'sample.html',
      controller: 'MyController'
    });

完整的样本将是这样的:

angular.module('demo', ['ngRoute'])
    .controller('MainController', function($scope, $route, $routeParams, $location) {
    })

   .controller('SampleController', function($scope, $routeParams) {
       $scope.name = "SampleController";
       $scope.params = $routeParams;
   })
  .config(function($routeProvider, $locationProvider) {
    $routeProvider
    .when('/entries/:id', {
      templateUrl: 'sample.html',
      controller: 'SampleController'
    });

    // configure html5 to get links working on jsfiddle
    $locationProvider.html5Mode(true);
  });