How to flatten with ng-repeat

妖精的绣舞 提交于 2019-12-31 00:46:12

问题


I have:

    businesses: [
    {businessName: 'A', "address":[loc1, loc2, loc3]},
    {businessName: 'B', "address":[loc1, loc2]},
    {businessName: 'C', "address":[loc1]}
};

I want to ng-repeat this object with output:

A | street, city, zip, state 
A | street, city, zip, state 
A | street, city, zip, state 
B | street, city, zip, state 
B | street, city, zip, state 
C | street, city, zip, state 

In other words, i want to display this object as flat in a table with ng-repeat.

Do i have to flatten it myself, or does ng-repeat have the power to do this?

Ideally i could just do something like

ng-repeat business in businesses
business.businessName | business.address.City | business.address.State

By specifying address, it should know i want them all.

Otherwise, how do i flatted an object like this one?

Thanks!


回答1:


Seems like you could process it a bit, something like:

var flatBusinesses = [];
for (business in businesses) {
    for (address in business.addresses) {
        flatBusinesses.push ({name: business.name, address: address.City, state: address.State}
    }
}

And then just repeat on flatBusinesses in the view




回答2:


The underscore library has a number of functions for dealing with javascript arrays and objects that work well as a complement to angular:

http://underscorejs.org/

You would need to download the library and add it to your project.

Then you could write:

var flatBusinesses = _.flatten(_.pluck(businesses, 'address'));

You should be able to add the underscore library to the scope:

$scope._ = _;

And then add this directly to your template:

<div ng-repeat="business in _.flatten(_.pluck(businesses, 'address'))">
{{business.businessName}} | {{business.address.City}} | {{business.address.State}}
</div>

EDIT:

So, I didn't read your questions carefully enough, and flatten and pluck aren't going to cut it in your case.

I put together a fiddle playing around with underscore to make it work, but the final result is not an improvement over rquinn's response.

Anyways, here is the fiddle if you want to look at it: http://jsfiddle.net/pna7f5h3/



来源:https://stackoverflow.com/questions/17076168/how-to-flatten-with-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!