获取最外层ng-repeat中嵌套ng-repeat的计数,并根据ng-model值

时间:2017-07-09 18:33:29

标签: html angularjs angularjs-ng-repeat angularjs-filter angularjs-ng-model

我有三个嵌套的ng-repeat来显示驱动器对应的文件夹及其相应的文件。样本数据如下所示

Drives=[  
   {  
      name:'C Drive',
      folders:[  
         {  
            name:'personal',
            files:[  
               {  
                  name:'a.txt'
               },
               {  
                  name:'b.txt'
               }
            ]
         }
      ]
   }
]

所以我有三个嵌套的ng-repeat来显示驱动器名称,文件夹和文件夹中的文件。 如何获取驱动器中的文件总数并沿驱动器名称显示它。

示例代码

<div ng-repeat="drive in drives">
{{drive.name}} <I want the total count of files in a drive here>
    <div ng-repeat="folder in drive.folders">
    {{folder.name}} {{filteredfiles.length}}
        <div ng-repeat="file in filteredfiles=(folder.files | filter 
        {name:search})">
        {{file.name}}
        </div>
    </div>
</div>
<input type="text" ng-model="search"/>

请注意,我有一个搜索过滤器,因此驱动器中的文件数应根据应用的过滤器值动态更新,以表示与特定驱动器中的搜索值同名的文件数。

如何逐步计算驱动器中的文件数量并应用双向绑定,以便根据搜索值更新计数?

对于Angular版本1.6

2 个答案:

答案 0 :(得分:0)

有两种方法可以解决这个问题。如果使用组件并且组件是适当嵌套的,那么您可以简单地将子组件定义中的变量传递给它:

.component('ComponentName', {
    bindings: {
          myVariable: '=' //Look up the appropriate sigil for the binding behavior you want
        }, 
`//....rest of component def here

    })

然后,您只需通过您在路由器中制作的指令(或实例化组件时)将其移交给

<my-directive my-variable="$ctrl.myVariable"></my-directive>

示例:https://toddmotto.com/one-way-data-binding-in-angular-1-5/

或者,您只需创建一个服务并使其成为两个控制器中的依赖项,并通过getter / setter设置值,因为服务是单例并且可以维护控制器之间的值。

答案 1 :(得分:0)

修改filteredfiles,使它们包含在一个控制器对象中,您可以迭代它以获得所有数组的总长度。使用第一级键的驱动器索引和下一级别的文件夹索引。

然后使用一个使用Array#reduce(或for in循环)的控制器函数来迭代所有各种对象键以汇总所有数组长度

查看:

 <div ng-repeat="drive in drives">

    <strong>{{drive.name}}</strong>  -- File count:{{filteredFileCount($index)}}

    <div ng-repeat="folder in drive.folders" ng-init="driveIndex = $parent.$index">
     {{folder.name}} has {{filteredfiles[driveIndex][$index].length}} files
     <ul>
        <li ng-repeat="file in filteredfiles[driveIndex][$index]=(folder.files | filter:{name:search} ) ">
        {{file.name}}
      </li>
     </ul>

    </div>
  </div>

控制器:(或将业务逻辑投入使用)

  // object to hold arrays filtered in view
  $scope.filteredfiles = {};

  $scope.filteredFileCount = function(driveIndex) {

    let driveObj = $scope.filteredfiles[driveIndex] || {};

    return  Object.keys(driveObj).reduce((a, c) => {
      return a + (Array.isArray(driveObj[c]) ? driveObj[c].length : 0);
    }, 0);

  }

DEMO