angularJS: вложенный ng-repeat, orderBy не работает - PullRequest
0 голосов
/ 29 мая 2018

Я работаю с angular, пытаясь использовать orderBy для вложенного ng-повторения (на обоих), но безуспешно.Пожалуйста, посмотрите:

вот мой взгляд:

<article class="unaTienda"
    ng-repeat="tienda in resumenesRondaInventariosPorTienda | orderBy: ID_CO" >
    <h3 class='bold'>{{tienda[0][0].nombreTienda}}</h3>
    <article class="unDocumento" ng-repeat="documento in tienda[$index]" >
        <h3>{{documento.tipoDocumento}} {{documento.numeroDocumento}}</h3>
    </article>
</article>

Это моя модель для этого представления, $ scope.resumenesRondaInventariosPorTienda:

    {  
   "0":[  
      [  
         {  
            "ID_CO":20,
            "nombreTienda":"GIRARDOT",
            "fechaDocumento":"20151204",
            "tipoDocumento":"IF",
            "numeroDocumento":1,
            "unidades":-12,
            "pesos":-128517
         },
         {  
            "ID_CO":20,
            "nombreTienda":"GIRARDOT",
            "fechaDocumento":"20180409",
            "tipoDocumento":"IF",
            "numeroDocumento":16,
            "unidades":5,
            "pesos":28870
         }
      ]
   ],
   "1":[  
      [  
         {  
            "ID_CO":2,
            "nombreTienda":"PLAZA CAICEDO",
            "fechaDocumento":"20160115",
            "tipoDocumento":"IF",
            "numeroDocumento":1,
            "unidades":-8,
            "pesos":84701
         },
         {  
            "ID_CO":2,
            "nombreTienda":"PLAZA CAICEDO",
            "fechaDocumento":"20180417",
            "tipoDocumento":"IF",
            "numeroDocumento":16,
            "unidades":-6,
            "pesos":-59361
         }
      ]
   ]
}

Ответы [ 2 ]

0 голосов
/ 29 мая 2018

Джон правильно понял, что было бы лучше сначала поместить данные вашего объекта в массив, а затем упорядочить их в разметке (намного проще).Я действовал в предположении, что вы не можете связываться со структурой данных ...

Итак!Если вам когда-либо понадобится сделать пользовательскую функцию фильтра - вот вам:

Plunkr

// I like to wrap my JS files in IIFE's per the John Papa Style Guide

(function() {

  "use strict";

  let app = angular.module('myApp', []);

  app.filter('resumenes', resumenesFunc);

  app.controller('myCtrl', myCtrlFunc);

  myCtrlFunc.$inject = ["$scope"];

  // Custom Filter Function
  function resumenesFunc() {
    return function(resumenes) {
      let resumenesArr = [];

      // Putting the resumenes into a single Array
      for (let resumenIndex in resumenes) {
        let innerArr = resumenes[resumenIndex];

        innerArr.forEach(r => {
          resumenesArr.push(r);
        })
      }

      return resumenesArr.sort(function(a, b) {
        return a.numeroDocumento - b.numeroDocumento;
      });
    }
  }

  // Controller Function
  function myCtrlFunc($scope) {
    $scope.resumenesRondaInventariosPorTienda = {
      "1": [{
        "ID_CO": 1,
        "nombreTienda": "UNICENTRO CALI",
        "fechaDocumento": "20160126",
        "tipoDocumento": "IF",
        "numeroDocumento": 1,
        "unidades": -19,
        "pesos": -213310
      }, {
        "ID_CO": 1,
        "nombreTienda": "UNICENTRO CALI",
        "fechaDocumento": "20180423",
        "tipoDocumento": "IF",
        "numeroDocumento": 16,
        "unidades": -2,
        "pesos": -11485
      }],
      "2": [{
        "ID_CO": 2,
        "nombreTienda": "PLAZA CAICEDO ",
        "fechaDocumento": "20160115",
        "tipoDocumento": "IF",
        "numeroDocumento": 1,
        "unidades": -8,
        "pesos": 84701
      }, {
        "ID_CO": 2,
        "nombreTienda": "PLAZA CAICEDO ",
        "fechaDocumento": "20160223",
        "tipoDocumento": "IF",
        "numeroDocumento": 2,
        "unidades": -25,
        "pesos": -556909
      }]
    }
  }

})()
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>AngularJS Test App</title>

  <link data-require="bootstrap@3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" href="style.css" />

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script data-require="bootstrap@3.3.7" data-semver="3.3.7" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>

  <script src="app.js"></script>

</head>

<body>
  <h2>Custom Filter - Resumenes</h2>
  <div ng-app="myApp" ng-controller="myCtrl" ng-init="quantity = 10; cost = 5">
    <article ng-repeat="tienda in resumenesRondaInventariosPorTienda | resumenes">

      <!-- Custom Filter returns an array rather than an object - so no need for the second repeat -->
      <article class="unDocumento">
        <h3>{{tienda.tipoDocumento}} {{tienda.numeroDocumento}}</h3>
      </article>

    </article>
  </div>
</body>

</html>

Редактировать : я забыл упомянуть, что пользовательский фильтр возвращает массив резюме - так что обратите внимание, что я вынул ваш второй ng-repeat в разметке.Мы выполняем всю работу в функции фильтра для этого объекта данных ... нет причин для нас добавлять дополнительную разметку.

Отказ от ответственности : Я не вдавался в сумасшедшие подробности (иначе обработка ошибок и тому подобное; вы можете добавлять их по мере необходимости).=)

0 голосов
/ 29 мая 2018

Ваш $scope.resumenesRondaInventariosPorTienda является объектом, в котором он должен быть массивом.

Повторно манипулируйте вашими данными

$scope.final = [];
for(var x in $scope.resumenesRondaInventariosPorTienda)
{
  $scope.final.push($scope.resumenesRondaInventariosPorTienda[x]);
}

Тогда, на ваш взгляд, это должно быть так

<article ng-repeat="tienda in final | orderBy: tienda[$index].ID_CO" >
    <article class="unDocumento" ng-repeat="documento in tienda | filter:busqueda" >
        <h3>{{documento.tipoDocumento}} {{documento.numeroDocumento}}</h3>
    </article>
</article>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...