0

I’m trying to toggle the visibility of a div in angular This is my view:

<div ng-repeat="item in data  | orderBy:'address' | groupBy:'address'" >
    <h5 onclick="toggle_visibility('item1');">{{item.address}}</h5>
      <div id="item1">
           <ul>
               <li>First Name: {{item.firstname}}  </li>
           </ul>
      </div>

In controller:

$scope.data = [
        {
            firstname: "user",
            address: “address1”
        },
        {
            firstname: "user1",
            address: “address2”
        },
        {
            firstname: "user2",
            address: “address1”
        }
    ];

The issue is when I click on any address header it hides or shows the first name within the first header and it should be when I click on the address header it shows or hides the first name within that address header that I clicked on it. How can I fix this?

Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80

2 Answers2

0

Html

<div ng-repeat="item in data  | orderBy:'address' | groupBy:'address'" >
    <h5 ng-click="toggle_visibility(item);">{{item.address}}</h5>
      <div ng-hide="item.invisible">
           <ul>
               <li>First Name: {{item.firstname}}  </li>
           </ul>
      </div>

JS

$scope.toggle_visibility = function(item) {
    item.invisible = !item.invisible
}
Gaurav Kumar Singh
  • 1,550
  • 3
  • 11
  • 31
0

add additional boolean property to array and assign that property to ng-hide. then inside click function change the boolean value of that property.

angular.module("app",[])
.controller("ctrl",function($scope){
 $scope.data = [
        {
            firstname: "user",
            address: "address1",
            hideAddress : false
        },
        {
            firstname: "user1",
            address: "address2",
            hideAddress : false
        },
        {
            firstname: "user2",
            address: "address3",
            hideAddress : false
        }
    ];
    
    $scope.toggle_visibility = function(item){
       item.hideAddress = !item.hideAddress;
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div ng-repeat="item in data  | orderBy:'address' " >
    <h5 ng-click="toggle_visibility(item);">{{item.address}}</h5>
      <div ng-hide="item.hideAddress">
           <ul>
               <li>First Name: {{item.firstname}}  </li>
           </ul>
      </div>
    </div>
</div>
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80