【问题标题】:AngularJS: Add toggle function to an image inside ng-repeatAngularJS:向 ng-repeat 中的图像添加切换功能
【发布时间】:2016-04-27 14:06:51
【问题描述】:

我将 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:

【问题讨论】:

    标签: javascript html angularjs


    【解决方案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]">
    

    【讨论】:

    • 感谢您的快速回复。我试过了,但得到 TypeError: Cannot read property '2' of undefined。当我点击图片时。
    • 你定义了$scope.items 吗?
    • 谢谢。更新了我的答案。
    猜你喜欢
    • 2016-05-31
    • 2015-04-11
    • 1970-01-01
    • 2017-06-24
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多