问题
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