Vitaly Menchikovsky
Vitaly Menchikovsky

Reputation: 8904

How to show proprty from array by keys from anther array

I am trying to show data from 2 array based on same key, the example is

firstArray

[{$id='12321',name='test'},{$id='12312',name='test'},{$id='1234',name='test'}]

second array:

[{$id='12321',value=4},{$id='12312',value=2}]

how can I display with ng-repeat the first array and if second have this id to show the value.

I tried to do

 <div ng-repeat="qu in vm.qus">
                <div ng-repeat="max in vm.maxs | filter :{ max.$id === qu.$id } ">

the error:

Error: [$parse:syntax] Syntax Error: Token '.' is unexpected, expecting [}] at column 34 of the expression

Upvotes: 0

Views: 32

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

You had syntactical mistake, it should be

<div ng-repeat="max in vm.maxs | filter :{ max: {$id :qu.$id } }: true as filtered">

Though the better way of filtering collection is controller, as it will evaluate only once where, applying filtering on html itself got evaluated on each digest cycle(expensive in terms of performance)

vm.filterd = $filter('filter')(vm.maxs, { max: {$id :qu.$id } }, true);

But then you have to again think about to make sure you're applying above for each question.

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222672

You can use ng-if,

 <div ng-repeat="qu in vm.qus">
    <div ng-repeat="max in vm.maxs" ng-if="max.$id ===qu.$id">
      {{max}}
    </div>
  </div>

DEMO

var app = angular.module('app', []);
app.controller('demoCtrl', ['$scope', function($scope) {
  vm = this;
  vm.qus = [{
    $id: '12321',
    value: 4
  }, {
    $id: '12312',
    value: 2
  }];

  vm.maxs = [{
    $id: '12321',
    value: 4
  }, {
    $id: '12312',
    value: 2
  }]
}]);
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title></title>
</head>

<body ng-app="app" ng-controller="demoCtrl as vm">
  <div ng-repeat="qu in vm.qus">
    <div ng-repeat="max in vm.maxs" ng-if="max.$id ===qu.$id">
      {{max}}
    </div>
  </div>
  <script type=" text/javascript " src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.js "></script>
  <script type="text/javascript " src="MainViewController.js "></script>
</body>

</html>

Upvotes: 1

Related Questions