通过URL参数将id传递给Angular

Pass id to Angular by URL parameter

本文关键字:Angular id URL 参数 通过      更新时间:2023-09-26

在我的应用程序中,我确实有一个列表视图和单个列表项的详细视图。单击列表条目即可打开详细视图。这很好用。但是,现在我想在电子邮件中提供链接,以便直接访问详细的项目视图。

我发现,我可能需要ngRoute来实现这一点,但它并没有按预期工作。事实上,它根本不起作用。我的alert()函数从未被调用。

这是我的控制器的相关部分:

var myController = angular.module('myProject.controllers', ['ngRoute']);
myController.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $routeProvider.when('/show/:itemId', {
    templateUrl: 'item-details.html',
    controller: 'MyController'
  });
  $locationProvider.html5Mode(true);
}]);
myController.controller('MyController', ['$scope', '$routeParams', function($scope, $routeParams) {
  /** Other stuff... */
  $scope.$on('$routeChangeSuccess', function() {
    // $routeParams should be populated here
    alert("itemId: " + $routeParams.itemId);
    if ($routeParams.item) {
      myFunction($routeParams.itemId);
    }
  });
}]);

我试着用两个调用我的页面

http://www.example.com/index.html#/show/123

http://www.example.com/show/123

但都没有奏效。我做错了什么吗?

我过去也遇到过同样的问题,我只是使用了Jquery函数

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;
    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

$scope.item = getUrlParameter('show');

但您需要将链接更改为以下内容:

http://dummy.com/?show=123

希望这行得通,对我来说还是行的。不过不知道这是不是一个恶作剧。

我设法使用$location依赖项通过URL将参数传递给我的控制器:

var myController = angular.module('myProject.controllers', []);
myController.config(['$locationProvider', function($locationProvider) {
  $locationProvider.html5Mode(true);
}]);
myController.controller('MyController', ['$scope', '$location', function($scope, $location) {
  /** Other stuff... */
  /** index.html?itemId=123 */
  var id = $location.search().itemId;
  if (id) {
    alert("Item id: " + id);
    myFunction(id);
  }
}]);

这在传递给控制器的参数方面起作用。然而,这给我留下了一个问题:我界面中的所有ngClick按钮现在都会附加查询参数,这有点烦人,因为例如,我不想将itemId附加到back按钮上。

如果我找到任何解决方案,我会设法解决这个问题,并向您汇报。

这篇博文对$location很有帮助。