javascript - AngularJS:向 ng-repeat 内的图像添加切换功能

标签 javascript html angularjs

我正在使用 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]">

关于javascript - AngularJS:向 ng-repeat 内的图像添加切换功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36892253/

相关文章:

Javascript解码html实体

javascript - 根据状态变化仅将样式应用于一个 div

javascript - 如何从 Javascript 调用 PHP 文件并将数据从 PHP 返回到 Javascript

javascript - AngularJS Ng-repeat,用表达式创建动态 dom

angularjs - 禁用或隐藏选定的 ng-options angularjs

javascript - 我应该将事件监听器代码放在所有 Controller 都使用的 AngularJS 中的什么位置?

javascript - jQuery 加载函数内部的 jQuery 加载函数

javascript - GroupBy CSV 文件中的数组元素并有助于减少代码

html - Bootstrap 网站 jumbotron 图像缩放

html - 在 Firefox 上强制打印背景颜色