javascript - 无法在表中显示正确的数据 -AngularJS

标签 javascript arrays angularjs angularjs-ng-repeat

下面是我的 plunker,我尝试在每个类别下显示数据。但是数据没有按预期打印。示例:-rom 值 12345 应该直接位于面包下​​。 我不确定我的代码哪里做错了:

  $scope.allProducts = [];
  angular.forEach($scope.data,function(item, index){
    angular.forEach(item.products, function(item2, index){
      if($scope.allProducts.indexOf(item2.consummable) == -1){
        $scope.allProducts.push(item2.consummable);
      }
    })
  })

Creating a table matrix

最佳答案

又一个变体,改变了 ng-repeat 表达式。由于您在第一行重复allProducts,因此您需要在其他行中重复它,并过滤所选值的数据。请参阅下面的代码片段

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.data =[
    {
        "resource": "100",
        products: [
            {
                "consummable": "milk",
                 "rom": 1
            },
         
        ]
    },
    {
        "resource": "200",
        products: [
        
            {
                "consummable": "bread",
                 "rom": 12345
            },
           
        ]
    },
    {
        "resource": "300",
        products: [
      
            {
                "consummable": "butter",
                 "rom": 123456789
            }
        ]
    }
];

  $scope.allProducts = [];
  angular.forEach($scope.data,function(item, index){
    angular.forEach(item.products, function(item2, index){
      if($scope.allProducts.indexOf(item2.consummable) == -1){
        $scope.allProducts.push(item2.consummable);
      }
    })
  })

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.17/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>

  <table style="border:1px solid red;">
    <tr>
      <td>
      </td>
      <td ng-repeat="itemProd in allProducts" style="border:1px solid red;">
        {{itemProd}}
      </td>
    </tr>
    <tr ng-repeat="item in data">
      <td>
        {{item.resource}}
      </td>
      <td ng-repeat="item2 in allProducts" style="border:1px solid red;" ng-init="product=(item.products | filter: {consummable:item2})[0]">
        <a>{{product.rom}}</a>
      </td>
    </tr>
  </table>
  {{allProducts}}
  {{data}}
  
</div>

关于javascript - 无法在表中显示正确的数据 -AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32517107/

相关文章:

javascript - angular2 : why window. location.href 会导致 Firefox 上的页面刷新,但 href 不会

javascript - 如何使用 JavaScript 将用户输入从表单呈现到另一个页面

javascript - AngularJs 将参数值传递给 Controller

javascript - 我如何在angularjs中滚动一个div

javascript - 如何通过对特定 Controller 和操作使用 Ajax 调用来重定向用户

javascript - ng-if 中丢失了表单功能

JavaScript - 替换对象中的数组值

arrays - Cantor 的 ZigZag 函数 : Find the nth cell

javascript - 将 javascript 对象映射到数组结构

angularjs - 如何刷新使用 AngularJS 中的 $resource 服务获取的本地数据