AngularJS - Watch multiple selects & HashSearch Altering

http://angularjs.org/

by programmieraffe

HTML

<script type="text/javascript" ng:autobind src="http://code.angularjs.org/0.9.19/angular-0.9.19.js"></script>

<div ng:controller="MainCtrl">
    <p>Hash-Search: {{$location.hashSearch}}</p>
    <br />
    Sort by: <select name="gridOptions.sort">
        <option value="ID">ID</option>
        <option value="name">Name</option>
    </select>
    <select name="gridOptions.sortDirection">
        <option value="ASC">asc</option>
        <option value="DESC">desc</option>
    </select>
    <br />
    Show <select name="gridOptions.limit">
        <option value="10">10</option>
        <option value="20">20</option>
    </select> datasets
    <br />
    <br />
    <p>Route - "reloadOnSearch:false" (See: <a href="https://groups.google.com/forum/#!topic/angular/iLXkHMZTVK0">Google Groups AngularJS</a>)</p>
</div>

JavaScript

function MainCtrl($route,$location){
    var self = this;
    
    this.$location = $location;
    // with reloadOnSearch:false we can prevent to reload the whole controller: $route.otherwise({reloadOnSearch:false});
    
    // multiple options
    this.$watch('gridOptions.sort + gridOptions.sortDirection + gridOptions.limit',function(newGridOptions){
        
        console.log('gridOptions changed',newGridOptions,self.gridOptions);
        // update hashSearch (route -> reloadOnSearch=false)
        $location.hashSearch = self.gridOptions; //Use the gridOptions the from self-scope! (newGridOptions is only a string)
    });
    
    this.$watch(function(){return $location.hashSearch;},function(hashSearch){
        console.log('hashSearch changed, reload the grid');
        // reload data here with new query parameters
    });   
    
    
}
MainCtrl.$inject = ['$route','$location'];