AngularJS: sync $location.search with an input value
By Anatoly Mironov
I have used AngularJS for a while and to me this seems to be the best MVC javascript framework. Today I wanted to implement a search which uses an input and a hash query string like in google. The input value and url have to be synced like:
index.html#?term=something
To do this we have to inject $location
into our angular control. See the Angular Guide about $location. Then we have to observe both the $scope.term (which is bound to the input value) and $location.search().
<!doctype html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js">
</script>
<script src="project.js"></script>
</head>
<body>
<h2>Hash Search</h2>
<div ng-controller="SearchCtrl">
<input type="text" ng-model="term"/>
</div>
</body>
</html>
and javascript (project.js): [sourcecode language=“javascript”] function SearchCtrl($scope, $location) { var termKey = “term”; $scope.$watch(function () { return $location.search(); }, function() { $scope.term = $location.search()[termKey] || “”; }); $scope.$watch(’term’, function(term) { $location.search(termKey, term); }); } [/sourcecode] In order to be able to listen to changes on $location.search, you have to provide an anonymous function in $watch. Thanks to Renan Tomal Fernandes’ answer on stackoverflow.
Comments from Wordpress.com
Nikita Tovstoles (@NikitaTovstoles) - Nov 6, 2013
how does the above not cause a circular loop (since two $watch invocations are ‘watching’ respective outputs)? thanks!
Ohar - Feb 3, 2016
Not triggering at $location.search(NAME, VAL);