在 angular 控制器中获取查询字符串

Get querystring in angular controller

我想得到一个 querystring 这是实际路由的一部分,这是实际的 url:
http://localhost:13453/Vehicle/Profile/c2db202f-9bf0-4876-851c-29964484bf7a

我想获取 Profile/

之后的最后一个值

如何在 angularJS 中实现这一点,然后我可以使用它来获取详细信息,例如:

.controller('VehicleProfileController', ['$scope', '$http', '$location',
  function ($scope, $http, $location) {
    //get the id here which I'll pass to $http call

     $http({
         method: 'GET',
         url: '/Vehicle/GetProfile'
     }).
     success(function (data) {

     });

}])

您可以使用 $stateProvider:

angular.module('vehicles').config(['$stateProvider',
    function($stateProvider) {
      $stateProvider.
            state('vehiclesId', {
                url: '/Vehicle/Profile/:id',
                templateUrl: 'modules/view.client.view.html'
            });

}]);

而不是只在控制器中使用:

angular.module('vehicles').controller('VehiclesController', ['$stateParams',
function($stateParams){

       $stateParams.id

}]);

正如@sma 在他的评论中所说,我们需要知道您使用的是什么路由器。

ui-路由器

如果您使用的是 ui-router 并且您在自己的状态下定义了参数,则可以只使用 $stateParams 以便在您的控制器中获取它:

app.controller('MyController', ['$stateParams', function ($stateParams) {
    var id = $stateParams.myParamName; // the param defined in the state
}]);

ngRoute

如果您使用的是 ngRoute,您应该以同样的方式使用 $routeParams

app.controller('MyController', ['$routeParams',
    function($routeParams) {
        var id = $routeParams.myParamName; // the param defined in your route
}]);

编辑

我假设你正在使用 ngRoute,所以首先,检查你的路由定义,它应该在你的 config 阶段,它应该是这样的:

.config(['$routeProvider',
    function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
      }).
      when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html',
        controller: 'PhoneDetailCtrl'
      }).
      otherwise({
        redirectTo: '/phones'
      });
}]);

然后,在您的控制器中,您应该能够像上面的 ngRoute 控制器示例(使用 $routeProvider)一样获取您的参数(在此示例中称为 phoneId) .

可能您应该首先查看文档,特别是 this part

如果你只需要一个直接的 javascript 解决方案,你可以使用类似下面的东西,而不必连接其他依赖项:

var loc = window.location.href; 
var id = loc.slice(loc.lastIndexOf('/'), loc.length).split('/')[1];

这里有一个快速 JSFiddle 可以玩。