ljerka ljerka - 3 months ago 7
AngularJS Question

How to "connect" 2 variables in Angular by some value

I have 2 variables in controller:

$scope.first = [
{ id="11", nameF="aaaa1" },
{ id="12", nameF="bbbb1" }
]

$scope.second = [
{ id="21", nameS="aaaa2", idFirst="11" },
{ id="22", nameS="bbbb2", idFirst="12" },
{ id="23", nameS="cccc2", idFirst="12" }
]


In a template I have ngRepeat for variable second:

<div ng-repeat="item in second>
<div>{{item.nameS}}</div>
<div>{{item.idFirst}}</div>
</div>


For every item.idFirst I would like to write out matching nameF instead. What is the best practice to achieve that? I can't seem to figure out a simple way to do it, but suppose there has to be one. Thanx!

Answer

If I understand correctly,

$scope.getNameF = function(idFirst){
    for(var i = 0; i < $scope.first.length; i++){
        if($scope.first[i].id === idFirst){
            return $scope.first[i].nameF;
        }
    }
    return undefined;
}

<div ng-repeat="item in second">
  <div>{{item.nameS}}</div>
  <div>{{getNameF(item.idFirst)}}</div>
</div>

EDIT

Also you can prepare data before rendering:

for(var i = 0; i < $scope.second.length; i++){
    $scope.second[i].nameF = getNameF($scope.second[i].idFirst);
}

<div ng-repeat="item in second">
  <div>{{item.nameS}}</div>
  <div>{{item.nameF}}</div>
</div>