Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Angular $location to set my new url location by changing its key-value params dynamically?

Let's say I have a RESTful endpoint that accepts a range of facets to query data. Here's a few examples:

example.com/search?type=Doctor&location=Boston,MA&radius=2  
example.com/search?type=Facility&location=Wayne,NJ&radius=3&gender=f  
example.com/search?type=Doctor&location=Patterson,NJ

My module accepts the query object to perform the search:

console.log(query);
{
  type:'Doctor',
  location:'Boston,MA',
  radius:'2'
}

$scope.getSearch = function(query){
  var search = $search.search(query);
  search.getResults(function(results){
    $scope.results = results;
  });
}

These facets are being passed through a local model in a web form:

 <input type="text" ng-model="query.location"/>
 <input type="text" ng-model="query.radius"/>
 <button type="button" ng-click="getSearch(query)">Search</button>

In the success callback of the getResults function, I'm trying to append the query parameters to the URL like in the examples above:

$scope.getSearch = function(query){
  var search = $search.search(query);
  search.getResults(function(results){
    $scope.results = results;
    search.appendQueryToURL(query);
  });
}

How do I append URL parameters dynamically in AngularJS?

like image 603
Dan Kanze Avatar asked Jul 05 '13 14:07

Dan Kanze


People also ask

How do I change the url in an angular application without reloading the route?

You could use location.go(url) which will basically change your url, without change in route of application.

What does the $location service do angular?

The $location service parses the URL in the browser address bar (based on the window. location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.

What is window location HREF in angular?

Window Location Href href property returns the URL of the current page.

What is location absUrl ()?

$location.absUrl() We can get full url of current web page. $location.url() It returns url without base prefix.


1 Answers

Using $location

$location.path('/newValue').search({key: value});

For Non AngularJS applications:

You can use history.js to append parameters dynamically to the url. then split the url to retrieve the params and pass to angular:

History.replaceState({state:1}, "State 1", "?Param1=something");

I am suggesting history.js as IE until ver9 didnt support history object push state, if you are going to use IE10+ or google chrome, use the history state object to update the url. Hope it helps :)

like image 123
neoeahit Avatar answered Oct 13 '22 09:10

neoeahit