Best way to toggle between parameters on ng-click

I am trying to have orderby for my search results. Instead of ordering with angular I want my server to do that. I am using rails and using ransack for searching..

So to make it work I need to pass ascending or descending to ransack.

So I created a link and used a ng-click and pass a parameter like below

 <a href="" ng-click="getRooms('price asc')">price</a>

This works as expected.

But when someone clicks on it I want the passed value to change from price asc to price desc. So in each click it toggles. Is it possible when using ng-click? The only thing I can think of is to use 2 links and hide the clicked ones but I think there should be another better way to do this..

Answers 1

  • You could create a variable in your controller that stores the current order (asc or desc). Then, just toggle this variable before making the call to the server every time the link is clicked.

    Sample implementation:

    Controller:

    $scope.order = 'asc'; // initial, default order
    
    function toggleOrder() {
        $scope.order = $scope.order == 'asc' ? 'dsc' : 'asc';
    }
    
    $scope.getRooms = function (columnName) {
        toggleOrder();
    
        // Make the call to the server using the columnName and $scope.order
    }
    

    HTML:

    <a href="" ng-click="getRooms('price')">price</a>
    

Related Articles