mailman_73 mailman_73 - 6 months ago 32
AngularJS Question

How to show more or less rows in a table by ng-click in angularjs with key, value pairs

I've got json where each parameter of the object has over 40

key, val
pairs. All data is put into a
html
table on a page
I want user to be able to change a number of rows on a
html
page.

Firstly, to reduce number of rows into the table I wrote
ng-if
statement. I added
ng-if
because
LimitTo
doesn't work with
key, val
pairs. And actually I'm stucking here. The main problem in
key, val
pairs for me.
How can I add more/less buttons that helps user hide or show more rows when a
json
file contains
key,val
pairs.

My
html


<table class="table ng-cloak" ng-if='$index<10' ng-repeat="shop in shops | filter:isActive">
<thead>
<tr>
<th>#</th>
<th>Месяц</th>
<th>Число кликов</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='(key, val) in shop.products' ng-if="$index < 10">
<td>{{ $index + 1 }}</td>
<td>{{ key }}</td>
<td>{{ val }}</td>
</tr>
</tbody>
</table>


my reduce
json


[
{
"products": {
"1359568800": 74,
"1361988000": 71,
"1364666400": 83,
"1367258400": 72,
"1369936800": 78
},
"name": "moskva",
"avg_check": {
"1359568800": 6479,
"1361988000": 7375,
"1364666400": 8477,
"1367258400": 9292,
"1369936800": 8357
},
"income": {
"1359568800": 479515,
"1361988000": 523662,
"1364666400": 703601,
"1367258400": 669072,
"1369936800": 651921
}
}
]

Answer

We cannot use default filter for objects. So use custom filter

app.filter('myLimitTo', [function(){
return function(obj, limit){
    var keys = Object.keys(obj);
    if(keys.length < 1){
        return [];
    }

    var ret = new Object,
    count = 0;
    angular.forEach(keys, function(key, arrayIndex){
       if(count >= limit){
            return false;
        }
        ret[key] = obj[key];
        count++;
    });
    return ret;
};

Checkout the Fiddle https://jsfiddle.net/ebinmanuval/uLo0bo0u/

Comments