sort with AngualrJS / orderBy by a field that will be created later

0

I'm using Ionic 1 with angular js.

I need to sort a result by a field that should be created later, the field is the distance from the first address of the company, in orderBy I do not know what to put, and also the object is not being generated correctly.

Or something that reorders the list right after the generation of the same.

Obs. I do not want to order the addresses within the company, I want to order the companies taking into consideration only the distance of the first address of each company. This distance will be calculated with the data taken from the user's GPS.

I made a JsFiddle that shows the situation

link

    
asked by anonymous 06.10.2017 / 15:00

1 answer

0

Here's the solution to your problem.

In addition to putting ng-init put a variable called $scope.predicate with the field you want to filter. Because it is a nested field, that is, the child of the elements of the array, you must define it in a variable so that the framework can interpret in the view.

function LoginController($scope) {
  $scope.parceiros = [
    {
      id: 1,
      nome: 'Empresa 1',
      enderecos: [
        {
          rua: 'dos bobos',
          numero: '0',
          lat: '-3.000000',
          long: '-3.000000'
        },
        {
          rua: 'dos bobos',
          numero: '230',
          lat: '-3.500000',
          long: '-3.500000'
        }
      ]
    },
        {
      id: 2,
      nome: 'Empresa 2',
      enderecos: [
        {
          rua: 'dos bobos',
          numero: '120',
          lat: '-3.700000',
          long: '-3.700000'
        },
        {
          rua: 'dos bobos',
          numero: '121',
          lat: '-3.200000',
          long: '-3.200000'
        }
      ]
    }
  ];
  
  $scope.predicate = 'enderecos[0].distancia';
    
  $scope.distancia = function(lat1, long1, userLat, userLong) {
  	
    return Math.floor((Math.random()*4)+1);
  };
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>Quandoadistanciadoprimeiroendereçodaempresa2formenorqueoprimeiroendereçodaempresa1,aordertemquesertrocada.<br>Obs.VaidandoRUNparaverquenadamuda,adistanciaéumrandom,somenteparaoexemplo.<br><divng-appng-controller="LoginController">
  <div ng-repeat="parceiro in parceiros | orderBy:predicate:reverse">
    <div style="border: 1px solid black;">
      {{parceiro.nome}}
      <div ng-repeat="endereco in parceiro.enderecos | orderBy: '+distancia'" ng-init="endereco.distancia = distancia(lat, long, 0, 0)">
        -- Rua: {{endereco.rua}} - Numero: {{endereco.numero}} - distância: {{endereco.distancia}}
      </div>
    </div>
  </div>
  
  
  <br>
  <br>
  <br>
  <br>
  <p>Aqui é só para mostrar que o campo foi criado dentro do objeto.</p>
  
  {{parceiros}}
</div>
    
09.10.2017 / 20:55