代码之家  ›  专栏  ›  技术社区  ›  IshCoo93

获取最外层ng重复中嵌套ng重复的计数,并根据ng模型值动态更新

  •  1
  • IshCoo93  · 技术社区  · 7 年前

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

    示例代码

    <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"/>
    

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

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

    2 回复  |  直到 7 年前
        1
  •  0
  •   charlietfl    7 年前

    修改 filteredfiles

    然后使用控制器函数,该函数使用 Array#reduce (或a 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

        2
  •  0
  •   Araymer    7 年前

    有两种方法可以解决这个问题。如果使用的组件和组件按其应有的方式进行了适当的嵌套,则只需在子组件定义中传递一个变量即可:

    .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/