简体   繁体   中英

How to get a url param in AngularJS

Any idea why $routeParams is logging undefined ? I would expect it to log an 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);
  }
]);

Current URL is http://localhost:3000/entries/5383a2f44d6f6816d7020000

I do NOT use return on my route configuration and I failed to find the templateUrl in your sample:

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

A complete sample will be like this:

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);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM