ahmdabos ahmdabos - 1 year ago 97
AngularJS Question

show item and hide the others elements within ng-repeat

I am trying to display list of names and when click on the name it will show the country for that name , and when click on other name it will hide the previous one and show the clicked one only,
i used ng-show with variable declared in the controller but it just keep showing each items i click on it without hiding the others, this is my code:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<div ng-repeat="x in records">
<a href="#" ng-click="showDesc = true">{{x.Name}}</a>
<div ng-show="showDesc">{{x.Country}}</div>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.showDesc = false;
$scope.records = [
"Name" : "Alfreds Futterkiste",
"Country" : "Germany"
"Name" : "Berglunds snabbköp",
"Country" : "Sweden"
"Name" : "Centro comercial Moctezuma",
"Country" : "Mexico"
"Name" : "Ernst Handel",
"Country" : "Austria"

Answer Source

ng-repeat has its own scope. So showDesc = true initializes a showDesc field in the ng-repeat scope. Each item has its own showDesc.

You want a global flag, common to all the items. And that can't just be a flag: you need to know which item must be expanded.

So just change the code to

$scope.expandedRecord = null;
$scope.expand = function(record) {
  $scope.expandedRecord = record;


<div ng-repeat="x in records">
  <a href="#" ng-click="expand(x)">{{x.Name}}</a>
  <div ng-show="expandedRecord === x">{{x.Country}}</div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download