How to flatten with ng-repeat

后端 未结 2 1515
[愿得一人]
[愿得一人] 2021-01-19 19:48

I have:

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


        
相关标签:
2条回答
  • 2021-01-19 20:02

    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

    0 讨论(0)
  • 2021-01-19 20:05

    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/

    0 讨论(0)
提交回复
热议问题