0

I need one help.I am unable to fetch some value as per some condition using angular.js.I am explaining my code below.

 var subcategories = [{
            id:1,
            name: 'SubCategory 1',
            value: 1
          }, {
            id:2,
            name: 'SubCategory 2',
            value: 2
          }, {
            id:3,
            name: 'SubCategory 3',
            value: 3
          }, {
            id:4,
            name: 'SubCategory 4',
            value: 4
          }];
    var result = $filter('filter')(subcategories, {id:1})[0];
    console.log('result',result);

Here i need to fetch all data whose id=1 from subcategories object. But in console i am getting result undefined. Please help me.

4
  • 1
    This code works as expected. The problem might be somewhere else. Commented May 24, 2016 at 13:46
  • 1
    Here's a Plunker with your code that shows it working. Commented May 24, 2016 at 13:46
  • duplicate maybe stackoverflow.com/questions/22851571/… Commented May 24, 2016 at 13:49
  • It would probably be easier to do subcategories.filter(sub => sub.id === 1) Commented May 24, 2016 at 13:53

1 Answer 1

0

Code works. Did you import the $filter directive into your controller??

https://jsfiddle.net/naLqezvs/

function Controller($scope,$filter) {
  $scope.subcategories = [{
        id:1,
        name: 'SubCategory 1',
        value: 1
      }, {
        id:2,
        name: 'SubCategory 2',
        value: 2
      }, {
        id:3,
        name: 'SubCategory 3',
        value: 3
      }, {
        id:4,
        name: 'SubCategory 4',
        value: 4
      }];
  $scope.results = $filter('filter')($scope.subcategories, {id:1});
  $scope.result = $scope.results[0];
}
Sign up to request clarification or add additional context in comments.

1 Comment

"But in console i am getting result undefined." If OP didn't inject $filter his code would probably fail with TypeError.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.