Vittal Das
Vittal Das

Reputation: 69

Linking two JSON object in AngularJs

I have 2 linked JSON object array .
Example :
Country :

[{
      "countryCode":"IN",
      "countryName":"India",
      "currencyCode":"INR"
   },
{
      "countryCode":"US",
      "countryName":"United States",
      "currencyCode":"USD"
   }]

Currency :

 [{
      "code":"INR",
      "name":"Indian Rupee",
      "locale":"kok_IN",
      "display":1
   }, {
      "code":"USD",
      "name":"US Dollar",
      "locale":"en_US_POSIX",
      "display":1
   }]

The above two json obejcts are linked with a code . I'm trying display the Currencyname from the currency object by linking the currencycode .
I am displaying like bellow :

<tr ng-repeat="country in countries | filter : query | orderBy : 'name'">
<td>{{ country.countryName }}</td>
<td>{{ }}</td> <!-- Currency name here -->
</tr>

How do I display the currency name here ?

Upvotes: 2

Views: 694

Answers (2)

Simon H
Simon H

Reputation: 21017

I would implement in a controller function

$scope.currencies = [{
    "code": "INR",
    "name": "Indian Rupee",
    "locale": "kok_IN",
    "display": 1
}, {
    "code": "USD",
    "name": "US Dollar",
    "locale": "en_US_POSIX",
    "display": 1
}];
$scope.getCurrency(code) {
    return $scope.currencies.find(c => c.code === code).name;
}

(Let me know if you need this in ES5 instead)

Then you can use

{{getCurrency(country.code)}}

Upvotes: 0

Emir Marques
Emir Marques

Reputation: 2687

Works for me with function getCurrencyByCountry:

angular.module("App", []).controller("AppController", function($scope) {
    $scope.countries = [{
        "countryCode": "IN",
        "countryName": "India",
        "currencyCode": "INR"
    }, {
        "countryCode": "US",
        "countryName": "United States",
        "currencyCode": "USD"
    }];
    
    $scope.currency = [{
        "code": "INR",
        "name": "Indian Rupee",
        "locale": "kok_IN",
        "display": 1
    }, {
        "code": "USD",
        "name": "US Dollar",
        "locale": "en_US_POSIX",
        "display": 1
    }];
    
    $scope.getCurrencyByCountry = function(country){
        var currency = "";
        angular.forEach($scope.currency, function(value, key) {
            if(country.currencyCode == value.code){
                currency = value.name;
                return false;
            }
        });
        return currency;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app="App" ng-controller="AppController">
  <tr ng-repeat="country in countries |orderBy : 'name'">
    <td>{{country.countryName}}</td>
    <td>{{getCurrencyByCountry(country)}}</td>
    <!-- Currency name here -->
  </tr>
<table>

Upvotes: 1

Related Questions