0

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

For example index.html?id=1234 should make make the controller load 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?

Community
  • 1
  • 1
idleberg
  • 12,634
  • 7
  • 43
  • 70

2 Answers2

2

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

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

Dima Pasko
  • 1,170
  • 12
  • 20
-1

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"];
Vaibhao
  • 31
  • 1