angularjs - 在点击时,我如何处理列表中的对象中的重复项,点击,手风琴打开?

时间:2016-01-03 18:29:31

标签: javascript angularjs ionic-framework ionic

我看了http://codepen.io/ionic/pen/uJkCz

这是我尝试的内容:http://codepen.io/anon/pen/rxjpwd

基本上,如果我的对象中有重复项,例如篮球比赛有3次,我怎样才能确保点击它只打开那个特定的篮球项目?

    var allGames = {
        "1": "Basketball",
        "2": "Baseball",
        "3": "Basketball",
        "4": "Football",
        "5": "Basketball"
      };
    $scope.games = allGames;

  $scope.toggleGames = function(game) {
    if ($scope.onTapGame(game)) {
      $scope.shown = null;
    } else {
      $scope.shown = game;
    }
  };
  $scope.onTapGame = function(game) {
    return $scope.shown === game;
  };

在我的模板中:

<div ng-repeat="game in games">
        <ion-item class="item item-button-right" ng-click="toggleGames(game)" ng-class="{active: onTapGame(game)}">
          {{game}}          
        </ion-item>
        <ion-item class="item-accordion" ng-show="onTapGame(game)">

        </ion-item>
      </div>

2 个答案:

答案 0 :(得分:0)

不要使用不必独特的值,而是使用必须唯一的键。

<div ng-repeat="(key, game) in games">
        <ion-item class="item item-button-right" ng-click="toggleGames(key)" ng-class="{active: onTapGame(key)}">
          {{game}}          
        </ion-item>
        <ion-item class="item-accordion" ng-show="onTapGame(key)">

        </ion-item>
 </div>

和你的AngularJS代码:

var allGames = {
    "1": "Basketball",
    "2": "Baseball",
    "3": "Basketball",
    "4": "Football",
    "5": "Basketball"
  };
$scope.games = allGames;

$scope.toggleGames = function(key) {
  if ($scope.onTapGame(key)) {
    $scope.shown = null;
  } else {
    $scope.shown = key;
  }
};
$scope.onTapGame = function(key) {
  return $scope.shown === key;
};

Working Codepen

答案 1 :(得分:0)

Ng-repeat指令在$ for each object if there are no track by {$scope.toggleGames = function(game) { if ($scope.onTapGame(game)) { $scope.shown = null; } else { $scope.shown = game.$$hashKey; } }; $scope.onTapGame = function(game) { return $scope.shown === game.$$hashKey; }; 下添加唯一标识符。因此,为了确保使用您需要的对象,您可以将代码更改为:

{{1}}