2016-04-27 69 views
0

我對div元素使用ng-repeat。 div元素中的圖像具有切換功能。但是,當我點擊圖像時,函數會被觸發,但它顯示的是所有div的相同數據。以下是代碼。AngularJS:將切換函數添加到ng-repeat內部的圖像

HTML:

<div ng-repeat="item in items"> 
    <div> 
     <img src="img/icon1.png" class="pull-right" ng-click="showDiv(item.itemId,$index)"> 
    </div> 
    <div ng-show="hiddenDiv[$index]"> 
     <div ng-repeat="student in studentData"> 
      <div class="row"> 
       <div> 
        <div>{{student.name}}</div> 
        <div>{{student.adress}}</div> 
       </div> 
      </div> 
     </div> 
    </div> 
</div> 

JS:

$scope.hiddenDiv=[]; 
$scope.showDiv=function(itemId,index) { 
    $scope.hiddenDiv[index] = !$scope.hiddenDiv[index]; 
    var myResult = ListService.getList(url here); 
    myResult.then(function (data) { 
     if(data && data.list) 
      $scope.studentData = data.list; 
    }); 
} 

在這裏,我正在使用的所有div內NG-重複同一範圍內的變量。

更新答:

JS:

$scope.studentData = []; 
$scope.studentData[index] = data.list; 

HTML:

回答

1

如果你想擁有獨一無二的學生每一個項目,你需要做這樣的事情:

<div ng-repeat="item in items"> 
    <div> 
     <img src="img/icon1.png" class="pull-right" ng-click="showDiv(item.itemId,$index)"> 
    </div> 
    <div ng-show="hiddenDiv[$index]"> 
     <div ng-repeat="student in item.studentData"> 
      <div class="row"> 
       <div> 
        <div>{{student.name}}</div> 
        <div>{{student.adress}}</div> 
       </div> 
      </div> 
     </div> 
    </div> 
</div> 

和JS:

$scope.hiddenDiv=[]; 
$scope.showDiv=function(itemId,index) { 
    $scope.hiddenDiv[index] = !$scope.hiddenDiv[index]; 
    var myResult = ListService.getList(url here); 
    myResult.then(function (data) { 
     if(data && data.list) 
      $scope.items[index].studentData = data.list; 
    }); 
} 

或使用相同hiddenDiv

$scope.hiddenDiv=[]; 
$scope.studentData = []; 
$scope.showDiv=function(itemId,index) { 
    $scope.hiddenDiv[index] = !$scope.hiddenDiv[index]; 
    var myResult = ListService.getList(url here); 
    myResult.then(function (data) { 
     if(data && data.list) 
      $scope.studentData[index].studentData = data.list; 
    }); 
} 

和HTML:

<div ng-repeat="student in studentData[$index]"> 
+0

感謝快速回復。我試過了,但得到** TypeError:無法讀取未定義**的屬性'2'。當我點擊圖像。 – NNR

+0

您是否定義了'$ scope.items'? – jcubic

+0

謝謝。更新了我的答案。 – NNR