Reputation: 53806
I'm attempting to pass a URL parameter to AngularJS controller using below code :
<div ng-app>
<div ng-controller="TodoCtrl" ng-init="init(getParameter('myParam'))">
</div>
</div>
function TodoCtrl($scope) {
$scope.init = function(category)
{
$scope.category = category;
alert(category);
};
}
function getParameter(theParameter) {
var params = window.location.search.substr(1).split('&');
for (var i = 0; i < params.length; i++) {
var p=params[i].split('=');
if (p[0] == theParameter) {
return decodeURIComponent(p[1]);
}
}
return false;
}
http://jsfiddle.net/U3pVM/15042?myParam=test
But it appears the function getParameter('myParam')
is not being invoked correctly I expect alert(category);
to display 'test' but instead it displays undefined
.
How to pass a URL parameter to AngularJS controller ?
Update :
Here is solution I went with :
alert(gup('category' , $location.absUrl()))
function getParameter( name, url ) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return results == null ? null : results[1];
}
Url is of form http://xxx.xxx.xxx?category=test
Upvotes: 0
Views: 1096
Reputation: 21209
Angular has built in helpers for reading and setting the url. In this case, use $location.search()
: (note that this snippet will only work on a page where the parameter is set!)
function TodoCtrl($scope, $location) {
var param = $location.search().myParam;
if(param) {
$scope.category = param;
alert(param);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="TodoCtrl">
</div>
</div>
Here, I "fake" set the parameter so you can see it in action:
function TodoCtrl($scope, $location) {
$location.search('myParam', 'myValue')
var param = $location.search().myParam;
if(param) {
$scope.category = param;
alert(param);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="TodoCtrl">
</div>
</div>
Upvotes: 1
Reputation: 19748
Don't use ng-init for anything but aliasing special properties of ng-repeat, see the ng-init docs for details. Instead if you need to read something from the URL parameters you can use $routeParams or $stateParams if you're using ngRoute or ui-router respectively or use $location.search
Upvotes: 0