GroupBy在角度过滤器中具有多个属性

时间:2016-09-15 06:56:11

标签: javascript angularjs angularjs-ng-repeat ng-repeat angularjs-filter

我有如下的json数据 [{ "id": 1, "address": "MG Road", "country": INDIA, "state": AP, "city": VIJ }, { "id": 2, "address": "Miyapur", "country": INDIA, "state": TS, "city": HYD }, { "id": 3, "address": "Autonagar", "country": INDIA, "state": AP, "city": VIJ }, { "id": 4, "address": "Kukatpalli", "country": INDIA, "state": TS, "city": HYD }, { "id": 5, "address": "Koti", "country": INDIA, "state": TS, "city": HYD } ]

我希望显示如下格式

IND,TS,HYD
      Miyapur,Koti,Kukatpalli
IND,AP,VIJ,
MG Road,Autonagar

对于即时通讯使用groupBy过滤器,如下所示,但我无法对这些值进行分组

这是我的代码

     <div class="location-container">
            <label ng-repeat="(key,value) in locationmodel | groupBy: '[country,state,city]'">{{key}}
            </label>
            <span ng-repeat="location in value">{{location.address}}</span>
      </div>

但是上面的代码我无法得到我所期望的。请帮我解决这个问题。

提前致谢

2 个答案:

答案 0 :(得分:1)

这是一个解决方案: https://jsfiddle.net/mqt0xjjc/

HTML:

<div ng-app="myApp">
<div  ng-controller="Main">
    <div ng-repeat=" (groupedBy, groupedItems) in locationmodelGrouped">
        <b>{{groupedBy}}</b>
        <li ng-repeat="item in groupedItems">{{item.address}}</li>        
    </div>
</div>
</div>

JS:

angular.module('myApp', []).controller( 'Main', 
function($scope) {
    function groupBy(items, groupByAttrs) {
        const retVal = items.reduce(
          function (sum, item) {
            const key = groupByAttrs.map( attr => item[attr]).join(',');
            sum[key] = sum[key] || [];
            sum[key].push(item);
            return sum;
          },
          {}
         );
      return retVal;
    };

    $scope.$watch('locationmodel',
        function () {
        $scope.locationmodelGrouped = groupBy($scope.locationmodel, ['country','state','city'])
      }
   )

$scope.locationmodel = [{
    "id": 1,
    "address": "MG Road",
    "country": 'INDIA',
    "state": 'AP',
    "city": 'VIJ'
},
{
    "id": 2,
    "address": "Miyapur",
    "country": 'INDIA',
    "state": 'TS',
    "city": 'HYD'
},
{
    "id": 3,
    "address": "Autonagar",
    "country": 'INDIA',
    "state": 'AP',
    "city": 'VIJ'
},
{
    "id": 4,
    "address": "Kukatpalli",
    "country": 'INDIA',
    "state": 'TS',
    "city": 'HYD'
},
{
    "id": 5,
    "address": "Koti",
    "country": 'INDIA',
    "state": 'TS',
    "city": 'HYD'
}
];

});

答案 1 :(得分:0)

如果您愿意,可以试试这个来获得输出

$utente = new Utente($db);
$var = $utente->login($_POST['nome_utente'], $_POST['password']);
if (!$var) {
    echo "The username doesnt match with the password!";
}