如何在 ng-repeat 中显示数组的特定字母表项?

how to show a particular alphabet item of array in ng-repeat?

我有两个数组,一个用于字母表,第二个用于标签.. 所以我只想显示该特定字母类别中的相同字母项目 示例 -- 苹果必须归入 A 类,动物园必须归入 Z 类...

fiddle link http://jsfiddle.net/4dGxn/149/

html

<div class="form-group" ng-controller="mainCtrl">
  <div ng-repeat="alp in alpha">
  <h2>{{alp}}</h2>
    <ul>
      <li ng-repeat="tag in tags">{{tag}}</li>
    </ul>
  </div>
</div>

angular

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

app.controller("mainCtrl", ['$scope', function($scope){

  $scope.alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p","q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

  $scope.tags = ["apple", "dog", "cat", "dad", "baby", "zoo", "love", "hate", "rat", "room", "home", "age", "bad"];

}]);

您可以使用 str.startsWith 检查元素是否以特定字符开头 所以在你的例子中:

<div class="form-group" ng-controller="mainCtrl">
  <div ng-repeat="alp in alpha">
  <h2>{{alp}}</h2>
    <ul>
      <li ng-repeat="tag in tags" ng-show="{{tag.startsWith(alp)}}">{{tag}}</li>
    </ul>
  </div>
</div>

这里是wirking Fiddle

您可以这样使用 filter

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

app.controller("mainCtrl", ['$scope', function($scope){

  $scope.alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p","q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

  $scope.tags = ["apple", "dog", "cat", "dad", "baby", "zoo", "love", "hate", "rat", "room", "home", "age", "bad"];

  $scope.f = function(alp) {
    return function(tag) {
      return tag[0] == alp;
    } 
  }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="form-group" ng-app="app" ng-controller="mainCtrl">
  <div ng-repeat="alp in alpha">
  <h2>{{alp}}</h2>
    <ul>
      <li ng-repeat="tag in tags | filter:f(alp)">{{tag}}</li>
    </ul>
  </div>
</div>

在第二个 ng-repeat 中使用自定义过滤器。

使用 ng-show 会在 alpha 组中创建不需要的 dom 元素。

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

app.controller("mainCtrl", ['$scope', function($scope){
 
  $scope.alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p","q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
  
  $scope.tags = ["apple", "dog", "cat", "dad", "baby", "zoo", "love", "hate", "rat", "room", "home", "age", "bad"];

 
}]);

app.filter('myfilter', function(){
    return function(input, text){
        // I recommend to use underscore lib for old browser.
        return input.filter(function(item){
            // I recommend to use standard regex for old browser.
            return item.startsWith(text);
        });
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">

<div class="form-group" ng-controller="mainCtrl">
  <div ng-repeat="alp in alpha">
  <h2>{{alp}}</h2>
    <ul>
     <li ng-repeat="tag in tags | myfilter:alp">{{tag}}</li>
    </ul>
  </div>
</div>
  </div>