AngularJS:将切换功能添加到ng-repeat内的图像

时间:2016-04-27 14:06:52

标签: javascript html angularjs

我正在使用ng-repeat for 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:

1 个答案:

答案 0 :(得分: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]">