Reputation: 12872
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?
Upvotes: 0
Views: 10354
Reputation: 31
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"];
Upvotes: -1
Reputation: 1170
$routeParams
is what you need.
Basicaly get your parameter like $routeParams.id
Additional information - https://docs.angularjs.org/api/ngRoute/service/$routeParams
Upvotes: 2