javascript 将 URL 参数传递给 AngularJS 控制器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26823667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:32:49  来源:igfitidea点击:

Pass URL parameter to AngularJS controller?

javascriptangularjs

提问by idleberg

In my app I'm reading an URL parameterwhich I'd like to pass to my Angular controller, which will then load a JSON file.

在我的应用程序中,我正在读取一个 URL 参数,我想将它传递给我的 Angular 控制器,然后它会加载一个 JSON 文件。

For example index.html?id=1234should make make the controller load data/1234.json

例如index.html?id=1234应该使控制器负载data/1234.json

My current code results in an injector error:

我当前的代码导致注入器错误:

var id = getUrlParam('id')

app.controller('myController', function ($scope, $http, id) {
  $http.get("data/"+id+".json").then(function(res) {
      $scope.posts = res.data
  })
});

What am I doing wrong?

我究竟做错了什么?

回答by Dima Pasko

$routeParamsis what you need. Basicaly get your parameter like $routeParams.id

$routeParams是你所需要的。基本上让你的参数像$routeParams.id

Additional information - https://docs.angularjs.org/api/ngRoute/service/$routeParams

附加信息 - https://docs.angularjs.org/api/ngRoute/service/$routeParams

回答by Vaibhao

Try this :

试试这个 :

var getParameterByName = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'))
var id = getParameterByName["id"];