过滤文件夹中的文件并使用ng-repeat(JS,Angular)显示它们

时间:2016-11-11 11:36:32

标签: javascript html angularjs

所以,我有一些包含未知数量文件的文件夹archives,我知道:

  • 所有文件都有.7z扩展名
  • 一半开始用字母AB和另一半 - CD

  • 所以文件夹的内容如下:
  • AB1234567890.7z
  • AB2345678901.7z
  • CD1234567890.7z
  • CD2345678901.7z
  • 我可以这样做:

    <a href="archives/AB1234567890.7z" download="{{fileName}}">Download</a>
    

    点击后,它将开始下载名为AB1234567890.7z的存档。没关系,但显然我不能写这样的链接,必须用ng-repeat来完成。所以问题是 - 如何显示2个链接列表,其中第一个列表将列出包含以AB秒<\ n开头的链接 - 分别以CD开头。任何帮助将不胜感激:)

    2 个答案:

    答案 0 :(得分:2)

    这个怎么样:

    &#13;
    &#13;
    angular.module('app',[]).controller('test', ['$scope', '$http', function($scope, $http){  
     //$http({ method: 'GET', url: '/getNames'}).then(function(names) {
     //    $scope.files = names;
     //}) 
      $scope.files = ['AB1234567890.7z',
                      'AB2345678901.7z',
                      'CD1234567890.7z',
                      'CD2345678901.7z'];
      $scope.startWith = function(file, name){    
          return file.indexOf(name) == 0;
      }
    }])
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app='app' ng-controller='test'>
    <p>First list</p>
      <div ng-repeat='file in files' ng-if="startWith(file, 'AB')">
        <a  href='archives/{{file}}'>{{file}}</a>
      </div>      
    <p>Second list</p>
      <div ng-repeat='file in files' ng-if="startWith(file, 'CD')">
        <a  href='archives/{{file}}'>{{file}}</a>
      </div>
    </div>
    &#13;
    &#13;
    &#13;

    答案 1 :(得分:0)

    我认为这会对你有帮助

    <div ng-controller="AppCtrl" layout="row" ng-cloak="" ng-app="MyApp">
      <div layout="column" flex>
          <a ng-repeat="file in archivesAB" href="archives/{{file}}" download="{{file}}">{{file}}</a>
      </div>
      <div layout="column" flex>
          <a ng-repeat="file in archivesCD" href="archives/{{file}}" download="{{file}}">{{file}}</a>
      </div>
    </div>
    
    (function () {
      'use strict';
       angular
         .module('MyApp',['ngMaterial', 'ngMessages',  'material.svgAssetsCache'])
         .controller('AppCtrl', AppCtrl);
    
       function AppCtrl ($scope, $log) {
         $scope.archivesAB = [
           'AB1234567890.7z',
           'AB2345678901.7z'
         ];
    
         $scope.archivesCD = [
           'CD1234567890.7z',
           'CD2345678901.7z'
         ];
    
       }
    })();
    

    这是工作codepen