0

I am using ng-repeat for div element. I have a toggle function on image inside div element. However, when I click on image, function gets triggered but it is showing up same data for all divs. Below is the code.

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

Here, I am using same scope variable in all divs inside ng-repeat.

Updated Answer :

js :

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

HTML :

1 Answer 1

1

If you want to have unique students for every item, you need to do something like this:

<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>

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

or use the same as for 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;
    });
}

and html:

<div ng-repeat="student in studentData[$index]">
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for quick reply. I tried, but getting TypeError: Cannot read property '2' of undefined. when I click on image.
Do you have $scope.items defined?
Thanks. Updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.