【问题标题】:$location service not passing URL Parameter to Controller$location 服务未将 URL 参数传递给控制器
【发布时间】:2017-02-07 14:21:34
【问题描述】:

我正在尝试通过 URL 参数将 ID 传递给名为“more.html”的页面。所以 URL 参数将如下所示。

http://example.com/more.html?id=200

我在 more.html 页面上的控制器中使用 $location 服务从 URL 获取参数 ID。这是我使用的控制器代码。

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($location, $scope, $http) {
    var sno = $location.search().id;
    alert(sno);
});

我从上面的代码得到的结果是“Undefined”。

【问题讨论】:

  • 尝试使用example.com/more.html#?id=200(添加'#'),但为什么不使用$state 而不是$location?一种更清洁和结构化的方法。 scotch.io/tutorials/angular-routing-using-ui-router
  • 问题是我通过链接传递 id。比如 list1list2。所以,我希望这是不可能的。
  • 所以...可以使用$state方法进行更改,不是吗?或更新网址。
  • 那告诉我这种情况下如何使用$state?
  • 如果你使用 angular-router 你可以通过使用 $routeParams 来实现

标签: angularjs


【解决方案1】:

就像@daan.desmedt 所说的那样。我将 URL 结构更改为以下并通过它传递 ID。

来自:

http://example.com/more.html?id=200

到:

http://example.com/more.html#?id=200

我在 more.html 之后添加了 #。它解决了这个问题。

【讨论】:

    【解决方案2】:

    将您的url structure 更改为如下(添加#

    来自:

    http://example.com/more.html?id=200
    

    到:

    http://example.com/more.html#?id=200
    

    在您的 url 参数之前添加 # more.html 将解决问题。 也许对于您的下一个项目,您可以使用ui-router,这是使用parameters 的一种更有条理的方式。

    https://github.com/angular-ui/ui-router

    【讨论】:

      【解决方案3】:

      你没有定义你注入的参数。它应该看起来像下面的代码:

      var app = angular.module('myApp', []);
      app.controller('customersCtrl', ['$location' , '$scope' , '$http' , function($location, $scope, $http) {
          var sno = $location.search().id;
          alert(sno);
      }]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多