Hekmat Sarwarzade
Hekmat Sarwarzade

Reputation: 143

Call a function in loop

The problem is that I have a list of people and their city id. I want to get the city name based on their id from another list by a function.

<table class="table">
<tr>
<th>#</th>
<th>Name</th>
<th>Type</th>
<th>City</th>
</tr>

<tr ng-repeat="item in samples">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.type}}</td>
<td>{{getCity(item.city)}}</td>
</tr>
</table>

and the controller:

$scope.samples = [
{id: 1, name: "alex", type: "Average", city: 12},
{id: 2, name: "Alex", type: "Average", city: 12},
{id: 3, name: "Mia", type: "Medium", city: 13},
{id: 4, name: "Sasha", type: "Top", city: 14},
{id: 5, name: "Eric", type: "Top", city: 12},
{id: 6, name: "Taz", type: "Average", city: 14},
{id: 7, name: "Normai", type: "Low", city: 13},
{id: 8, name: "Jim", type: "Average", city: 11}];


$scope.city = [
{id: 11, name: "Dallas"},
{id: 12, name: "Los Angeles"},
{id: 13, name: "New York"},
{id: 14, name: "Washington"}
];

$scope.getCity = function(name) { 
angular.forEach($scope.city, function(value, key){

  if(value.id == name){
    $scope.city_name = value.name;
  }
  return $scope.city_name;
  });
}

Here is a Fiddle for more details.

Upvotes: 0

Views: 2037

Answers (2)

chirag satapara
chirag satapara

Reputation: 1937

you are return value at wrong place. I just update the jsfiddle you can check here.

Here is the changes of the code.

$scope.getCity = function(name) {  
   $scope.city_name = "";
  angular.forEach($scope.city, function(value, key){ 
      if(value.id == name){
        $scope.city_name = value.name;
      } 
   });
  return $scope.city_name;
}

}]);

Upvotes: 2

byteC0de
byteC0de

Reputation: 5273

Try this function

$scope.getCity = function(id) {
  var city = $scope.city.filter(function(c){ return angular.equals(c.id, id); })[0];
  return city.name;
}

Upvotes: 0

Related Questions