Monojit Sarkar
Monojit Sarkar

Reputation: 2451

How to pass query string data or any value from url to controller function in AngularJS?

Suppose I have few links in page and each link has date like:

**https://mysite/blogs/01/01/2017
https://mysite/blogs/02/01/2017
https://mysite/blogs/03/01/2017
https://mysite/blogs/04/01/2017** 

How can I capture date and fetch data date wise when doing Angular routing ?

I am new so like to know how people pass query string data or any value from url to controller function with example code.

**https://mysite/blogs?custid=101&orderid=200
https://mysite/blogs/{customerid}/orders
https://mysite/blogs/{customerid}/{orderid}**

Please post a small sample code having controller, view and routing code if possible.

I am very eager to see how to handle query string or rest based URL kind with Angular routing which will pass data to controller and controller fetch data accordingly.

Upvotes: 0

Views: 1370

Answers (3)

This means that in all other cases that those mentionned in when clauses, the route is redirected to '/'. This solution shows how to use a different controller and route depending on the original url.

Upvotes: 0

You could use $location object. Here's a link to the official documentation

And here's a sample of code using it :

if ($location.hash() !== "") {
  $scope.date = $location.hash();
  $scope.loadData();
} else $scope.initWithDefaultValues();

But your url list should look like this :

**https://mysite/blogs#01/01/2017
https://mysite/blogs#02/01/2017
https://mysite/blogs#03/01/2017
https://mysite/blogs#04/01/2017** 

Once you did this, you can also set your browser url this way :

$location.hash( myUrlList[foo].split("#")[1] );

Where myUrlList contains your url list as shown upper.

In order this solution to work, you'll have to declare $http, $location, and perhaps also $anchorScroll depending of what you're doing with your date.

Upvotes: 1

Mistalis
Mistalis

Reputation: 18309

$routeProvider.when('/blogs/:day/:month/:year', {
    templateUrl: 'blog.html',
    controller: 'BlogCtrl'
});

Then in your controller, inject $routeParams to get the params:

function BlogCtrl($scope, $routeParams) {
    $scope.day = $routeParams.day;
    $scope.month = $routeParams.month;
    $scope.year = $routeParams.year;
}

Demo JSFiddle

Upvotes: 1

Related Questions