Searching through multiple ng-repeats at once

前端 未结 1 1659
盖世英雄少女心
盖世英雄少女心 2021-01-29 00:42

i\'m currently working on an application that is build with AngularJS as a base, and that obtains data through the prestashop webservice. All data obtained are JSON

相关标签:
1条回答
  • 2021-01-29 01:23

    I'd suggest to map your customers array adding to each object it's own place this way:

    $scope.customers.map( function addPlace(item) {
       item.place = $scope.addresses.reduce(function(a,b){
           return item.id === b.id_customer ? b.place : a;
       }, '');
       return item;
    })
    

    This way your template will be easier to read, and you will be able to use your previous search.

    angular.module('myApp', []).controller('namesCtrl', function($scope) {
        $scope.customers = [{
            'id': 1,
            'name': 'Jani'
            },{
            'id': 2,
            'name': 'Carl'
            },
            {
            'id': 3,
            'name': 'Tim'
            },
            {
            'id': 4,
            'name': 'Tom'
            }
        ];
        
        $scope.addresses = [{
            'id': 1,
            'id_customer': 1,
            'place': 'Street 12'
            },{
            'id': 2,
            'id_customer': 2,
            'place': 'Other street'
            },
            {
            'id': 3,
            'id_customer': 3,
            'place': 'marioworld!'
            },
            {
            'id': 4,
            'id_customer': 4,
            'place': 'Space!'
            }
        ];
    
        $scope.customers.map( function addPlace(item) {
           item.place = $scope.addresses.reduce(function(a,b){
               return item.id === b.id_customer ? b.place : a;
           }, '');
           return item;
        })
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="myApp">
      <div ng-controller="namesCtrl">
    
      <p><input type="text" ng-model="test"></p>
      <div ng-repeat="customer in customers | filter:test">
            {{ customer.id }} - {{ customer.name }}
            <br>
            {{ customer.place}}
        </div>
      </div>
    </div>

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