1

我正在尝试基于对象的动态数组创建一个开关...

例如:

  <div ng-switch on="currentItem">
    <div ng-repeat="item in myItems" ng-switch-when="item.name">
      <p>{{item.name}}</p>
      <button ng-click="nextItem(item)">Next Item</button>
    </div>
  </div>

然后在我的控制器中......

  $scope.myItems = [{
      "name": "one"
    }, {
      "name": "two"
    }]
    // Default first item
  $scope.currentItem = $scope.myItems[0].name;

  $scope.nextItem = function(med) {
    for (var i = 0; i < $scope.myItems.length; i++) {
      if ($scope.currentItem === $scope.myItems[i].name) {
        if ($scope.myItems[i + 1] !== undefined) {
          $scope.currentItem = $scope.myItems[i + 1].name
        }
      }
    }
  }

基本上,dom 应该为每个项目呈现一个 div,当用户单击 Next Item 按钮时, currentItem 应该被更新,并且应该基于此触发开关。

我没有看到我应该看到的第一个结果(没有呈现任何内容)。任何帮助将不胜感激。

Plunk:http ://plnkr.co/edit/PF9nncd1cJUNAjuAWK22?p=preview

4

2 回答 2

1

我已经分叉了你的 plunkr:http ://plnkr.co/edit/A9BPFAVRSHuWlmbV7HtP?p=preview

基本上你没有ngSwitch很好地使用。

只需使用ngIf

<div ng-repeat="item in myItems">
  <div ng-if="currentItem == item.name">
    <p>{{item.name}}</p>
    <button ng-click="nextItem(item)">Next Item</button>
  </div>
</div>
于 2015-12-23T18:49:40.153 回答
0

我已经分叉了你的 plunkr:http ://plnkr.co/edit/2doEyvdiFrV74UXqAPZu?p=preview

与 Ignacio Villaverde 类似,但我更新了获取 nextItem() 的方式。

$scope.nextItem = function() {
    var next = $scope.myItems[$scope.myItems.indexOf($scope.currentItem) + 1];
    if(next) {
      $scope.currentItem = next;
    }
  }

您可能应该在 currentItem 中保留对整个对象的引用,而不仅仅是名称:

<div ng-repeat="item in myItems">
<div ng-if="item == currentItem">
  <p>{{item.name}}</p>
  <button ng-click="nextItem(item)">Next Item</button>
</div>

简单多了!

于 2015-12-23T18:56:36.177 回答