0

I'm writing a search screen in AngularJS which fetches and displays the search results within the same page. I'd like the URL to reflect the parameters used in the search. What I've got so far (simplified):

<input type="text" ng-model="search.name"> <button ng-click="search()">Search</button> <ul> <li ng-repeat="widget in widgets">...</li> </ul> 

And the controller (Coffeescript):

module.controller "WidgetController", ($scope, $http, $routeParams, $location) -> if $routeParams.name $scope.search.name = $routeParams.name config = params: name: $routeParams.name $http.get("/api/widgets", config).success (data) -> $scope.widgets = data $scope.search = -> $location.path("widgets").search(name: $scope.search.name) 

This works fine -- when I click "Search", the URL is updated to reflect the query, and the results are returned.

The only problem is that if I do a search, then click the Search button again with the same query, the results are not refreshed. Presumably, the $location service sees that the current URL is already the same as the requested URL, and doesn't reload the view. Is there a good way to get it to do a refresh in this scenario?

1 Answer 1

1

I think that the problem here is that you depend on controller refreshing, what I would do is putting this bit as a method

doSearch = -> if $routeParams.name $scope.search.name = $routeParams.name config = params: name: $routeParams.name $http.get("/api/widgets", config).success (data) -> $scope.widgets = data 

then you can can run the search from search method

$scope.search = -> $location.path("widgets").search(name: $scope.search.name) doSearch() 

and to prevent controller from reloading you can set up correct value in route

Sign up to request clarification or add additional context in comments.

1 Comment

Nice suggestion, thanks. I ended up with $location.search(name: $scope.search.name), and setting reloadOnSearch: false in the $routeProvider. An alternative I tried was to run $route.reload() after updating the location, but I like your method better because it doesn't require reloading the view.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.