Joe82 Joe82 - 4 months ago 9
AngularJS Question

AngularJS - Filtering when targeting another page

I have built a simple filter with angularJS, the html is like

<a class="filterbutton" ng-click="filters.grade = '7'">7 Grade</a>
<a class="filterbutton" ng-click="filters.grade = '6'">6 Grade</a>
<a class="filterbutton" ng-click="filters.grade = ''">X Clear Filters</a>

<ul>
<li ng-repeat="name in names | filter:filters">{{name.student}}, {{name.grade}} grade</li>
</ul>


And the controller:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

$scope.filters = { };

$scope.names = [{
"student": "Jimmy", "grade":7
}, {
"student": "Johny", "grade":7
}, {
"student": "Little Joe", "grade":6
}];
});


This works as expected. But what I wanted to do is to be able to check one of the filters and jump to another page with the same controller, so that when loaded the second page would be already filtered. So for example, if I click "filter by 7 grade in another page", it would jump to anotherpage.html and the output there would be already filtered.

I have made a plunkr here to illustrate what I mean. Thanks in advance!

Answer

Also you can try this simple solution:

HTML (add filter parameter to href attribute):

<a class="filterbutton" href="anotherpage.html?filter=7">Filter by 7 Grade in Another Page</a>
<a class="filterbutton" href="anotherpage.html?filter=6">Filter by 6 Grade in Another Page</a>

Javascript (get them from url and apply it)

app.controller('myCtrl', function($scope) {

  $scope.filters = { grade : window.location.search.replace('?filter=','') };

  $scope.names = [{
    "student": "Jimmy", "grade":7
  }, {
    "student": "Johny", "grade":7
  }, {
    "student": "Little Joe", "grade":6
  }];

});
Comments