Show Description instead of angular value

Asked

Viewed 104 times

1

Hello, I am learning Angularjs and in my exercises I came across the following question: How do I show a description instead of a code. For example

$scope.aeronaves = [ cod_anv: '1', fabricante: '1' ];
$scope.fabricantes = [ cod_fab: '1', nome: 'Embraer' ];

I would like instead of showing {{aircraft.manufacturer}} which will be = 1, to show the name of the same that is in another array but related to my code.

Thank you in advance,

1 answer

2


First we need to adjust your collections, because the object statement is not correct:

[ cod_anv: '1', fabricante: '1' ] // colchetes ([]) definem uma coleção de objetos,
                                  // porém objetos precisam ser declarados com chaves ({})

Second, we create a map of the collection fabricantes indexed by the property cod_fab.

Finally, we instruct Angular to display the manufacturer’s name according to a searched index.

The code goes below:

function SampleController($scope) {
  
  $scope.aeronaves = [ {cod_anv: '1', fabricante: '1', modelo:'teste'}, 
                       {cod_anv: '2', fabricante: '2', modelo:'teste 2'},
                       {cod_anv: '3', fabricante: '1', modelo:'teste 3'},];
  $scope.fabricantes = [ {cod_fab: '1', nome: 'Embraer'},
                         {cod_fab: '2', nome: 'Boeing'} ];
  
  $scope.fabricantesMap = $scope.fabricantes.reduce(function (map, node) {
    map[node.cod_fab] = node;
    return map;
  }, {});
}
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </head>
  <body>
    <div ng-controller="SampleController">
      
      <div ng-repeat='i in aeronaves'>
        {{i.cod_anv}} - {{i.modelo}} - {{fabricantesMap[i.fabricante].nome}}
      </div>

    </div>
  </body>
</html>

  • Exactly that! Thank you for the lesson!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.