Search code examples
angularjsangular-ngmodelangularjs-ng-click

ng-click works only after filtering by typing into a field


I want to add to dir Paginate control filtering.

  <tr dir-paginate="advert in adverts |orderBy:propertyName:reverse | filter: searchAdvert | itemsPerPage: pageSize">

I have categoryId property in a model of my data and I want to filter it by using a choosing one of 4 buttons, so I wrote the code like:

    <button type="button" class="btn btn-default"   ng-click="applyFilter(3)">Items</button>
    <button type="button" class="btn btn-default"  ng-click="applyFilter(4)">Accomodation</button>

And in my controlles is:

$scope.applyFilter = function(object) {
    $scope.searchAdvert.categoryId = object;
}

});

However, it does not work. It worked for me only if I added following textbox:

        <input type="text" placeholder="Search by Category" ng-model="searchAdvert.categoryId" />

And if I write e.g. 1, then I can use the buttons and they work. I want to make it work without thix textbox ( only buttons)


Solution

  • Change your applyFilter to:

    $scope.applyFilter = function(object) {
        if(!$scope.searchAdvert)
           $scope.searchAdvert = {};
    
        $scope.searchAdvert.categoryId = object;
    }
    

    Your current code is trying to set a value categoryId on a null object. Your textbox example creates the $scope.searchAdvert object internally and allows the categoryId to be bound.