Reading Url Parameters In Angularjs - A Simple Way?
Solution 1:
You can inject the $location
service if you are using html5 mode.
Because you are using URLs without a base root (such as a ! or a #), you need to explicitly add a <base>
tag that defines the "root" of your application OR you can configure $locationProvider
to not require a base tag.
HTML:
<head><basehref="/">
...
</head><body><divng-controller="ParamsCtrl as vm">
...
</div></body>
JS:
app.config(['$locationProvider', function($locationProvider){
$locationProvider.html5Mode(true);
// or$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}]);
app.controller("TestCtrl", ['$location', function($location) {
var params = $location.search();
alert('Foo is: ' + params.foo + ' and bar is: ' + params.bar);
});
It is worth noting that you can add a router library such as ngRoute, ui-router or the new, unfinished component router. These routers rely on a base route off of a symbol (! or #) and define everything after the symbol as a client-side route which gets controlled by the router. This will allow your Angular app to function as a Single Page App and will give you access to $routeParams or the ui-router equivalent.
Solution 2:
You can use $location.search()
.
var parameters = $location.search();
console.log(parameters);
-> object{
foo: foovalue,
bar: barvalue
}
SO these values will be accessible with parameters.foo
and parameters.bar
Post a Comment for "Reading Url Parameters In Angularjs - A Simple Way?"