1

I have a factory in angular that will retrieve all data from the database as JSON data as below.

[{"part_no":"aaa","descr":"aaa123"},{"part_no":"bbb","descr":"bbb123"},{"part_no":"ccc","descr":"ccc123"},{"part_no":"ddd","descr":"ddd123"}]

How can i just filter, lets say the record with part_no : aaa and descr:aaa123 only?

maybe something like $scope.data = data | filter:part_no:aaa;

Joseph Goh
  • 689
  • 5
  • 16
  • 38
  • 1
    Do you want to prefilter results in factory, or filter it in `ng-repeat`? I think you will find the answer here: http://stackoverflow.com/questions/14302267/how-to-use-a-filter-in-a-controller – akn Apr 20 '16 at 06:59
  • 1
    thanks for the link, i ended using filterFilter builtin function – Joseph Goh Apr 20 '16 at 07:29

1 Answers1

1

Here's an example of how to filter both within JavaScript and within the view:

var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
  $scope.data = [{"part_no":"aaa","descr":"aaa123"},{"part_no":"bbb","descr":"bbb123"},{"part_no":"ccc","descr":"ccc123"},{"part_no":"ddd","descr":"ddd123"}];

  $scope.filteredData = $scope.data.filter(function(d) {
    return d.part_no === 'aaa' && d.descr === 'aaa123'
  });

});
.section {
  margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myctrl">
  <div class="section">
    <h3>unfiltered data:</h3>
    <div ng-repeat="item in data">Part: {{item.part_no}}, Description: {{item.descr}}</div>
  </div>
  <div class="section">
    <h3>pre-filtered data in JavaScript:</h3>
    <div ng-repeat="item in filteredData">Part: {{item.part_no}}, Description: {{item.descr}}</div>
  </div>
  <div class="section">
    <h3>filtered data in view:</h3>
    <input ng-model="partFilter" placeholder="part filter" />
    <input ng-model="descrFilter" placeholder="description filter" />
    <div ng-repeat="item in data | filter:{part_no: partFilter, descr: descrFilter}">Part: {{item.part_no}}, Description: {{item.descr}}</div>
  </div>
</div>
fikkatra
  • 5,605
  • 4
  • 40
  • 66