akrelj
akrelj

Reputation: 163

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!

Upvotes: 0

Views: 465

Answers (3)

Juha Tauriainen
Juha Tauriainen

Reputation: 1611

You can think of your template logic a bit like code, calling values from other variables: yourValue[another.value].nameF

Change your code to this and it should work

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

Upvotes: -1

scokmen
scokmen

Reputation: 571

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>

Upvotes: 1

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

You can use custom filter if you don't want to create one single object holding the expected structure.

HTML :

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

JS:

.filter('getMatchName', function() {

          return function(strName, arrFirst) {

            arrFirst.forEach(function(val, key) {

              if (val.id == strName) {
                strName = val.nameF;
              }

            })

            return strName;
          }
        })

Here is working plunker

Upvotes: 2

Related Questions