javascript - Reading URL parameters in AngularJS - A simple way? -
new angular here. come php , asp background, way read parameters this:
<html> <head> <script type="text/javascript"> var foo = <?php echo $_get['foo']; ?>; var bar = <?php echo $_get['bar']; ?>; $(document).ready(function() { alert('foo is: ' + foo + ' , bar is: ' + bar); }); </script> <head>
(it's not complete code, idea -- simple)
i've never done "client-side" query parsing before. correct method? i've posted question in past, i'm not getting answers. google searching not helping either.
my url typically in form of: example.com?foo=123&bar=456
is above syntax not supported these days? should doing like: example.com/foo/123/bar/345 instead?
i'm willing change url structure works cleanly angular, need pointed in right direction. example, i've heard of ngroute, have no idea start. correct approach?
i've posted question in past, didn't help, i'm re-posting more information it's more clear.
thanks pointers.
edit - using $location
note, i've tried using $location, has been unsuccessful me. see code below:
angular.module('myapp') .controller('mycontroller', ['$location', mycontroller]); function mycontroller($location) { var params = $location.search(); alert('foo is: ' + params.foo + ' , bar is: ' + params.bar); }
note: i've read setting $locationprovider.html5mode(true) in order style of query parsing work; however, i've been unsuccessful too.
you can inject $location
service if using html5 mode.
because using urls without base root (such ! or #), need explicitly add <base>
tag defines "root" of application or can configure $locationprovider
not require base tag.
html:
<head> <base href="/"> ... </head> <body> <div ng-controller="paramsctrl 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 + ' , bar is: ' + params.bar); });
it worth noting can add router library such ngroute, ui-router or new, unfinished component router. these routers rely on base route off of symbol (! or #) , define after symbol client-side route gets controlled router. allow angular app function single page app , give access $routeparams or ui-router equivalent.
Comments
Post a Comment