Show Description instead of non-angular value

1

Hello, I'm learning AngularJs and in my exercises I came across the following question: How do I show a description in place of a code. For example

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

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

Thank you in advance,

    
asked by anonymous 21.01.2016 / 21:30

1 answer

2

First we need to tweak your collections because the object declaration 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 created a map of the fabricantes collection indexed by the cod_fab property.

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

The code follows 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><divng-controller="SampleController">
      
      <div ng-repeat='i in aeronaves'>
        {{i.cod_anv}} - {{i.modelo}} - {{fabricantesMap[i.fabricante].nome}}
      </div>

    </div>
  </body>
</html>
    
21.01.2016 / 21:53