0

I have the following code:

$scope.a = true;
$scope.b = true;
$scope.c = true;

$scope.myData = [{att: 'a'},{att: 'b'},{att:'c'}  ]

What is the best way to filter out all objects that match the criteria above?

For example, right now I want all objects. However if $scope.a = false, I want to output only the 2nd and 3rd objects.

2 Answers 2

1

Have a look on what follows:

angular
  .module('test', [])
  .value('data', [{att: 'a'},{att: 'b'},{att:'c'}])
  .run(function($rootScope, data) {
  
    $rootScope.a = true;
    $rootScope.b = true;
    $rootScope.c = true;
    $rootScope.myData = data;
    
    $rootScope.update = function(value) {
      $rootScope[value] = !$rootScope[value];
      
      $rootScope.myData = data.filter((item) => $rootScope[item.att]);
    }
  })
.in {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<section ng-app="test">
  
  <button ng-class="{'in' : a}" ng-click="update('a')">a</button>
  <button ng-class="{'in' : b}" ng-click="update('b')">b</button>
  <button ng-class="{'in' : c}" ng-click="update('c')">c</button>

  
  <article ng-bind="myData | json"></article>
</section>

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the javascript array filter function like below

$scope.a = true;
$scope.b = false;
$scope.c = true;

$scope.myData = [{
    att: 'a'
}, {
    att: 'b'
}, {
    att: 'c'
}];


var res = $scope.myData.filter(function(obj) {
    if ($scope[obj.att]) return obj;
});

console.log(res);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.