AngularJS:为ng-repeat中的图像添加切换功能

AngularJS: Add toggle function to an image inside ng-repeat

本文关键字:添加 功能 图像 ng-repeat AngularJS      更新时间:2023-09-26

我正在使用ng-repeat来表示div元素。我在div 元素内的图像上有一个切换功能。但是,当我单击图像时,函数被触发,但它为所有div 显示相同的数据。下面是代码。

.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;
    });
}

在这里,我在 ng-repeat 内的所有div 中使用相同的范围变量。

更新的答案 :

.js:

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

.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 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]">