user1319501 user1319501 - 3 months ago 26
AngularJS Question

Deselect a selected row in ng-repeat

How do I deselect a row that I have just selected using the same button that I have used to select and highlight the row from an ng-repeat list? What different options are there, does anyone have any examples or links as I can't find any?

EDIT:-
Please see Plunker using link
https://plnkr.co/edit/LYrmpLUwGaWx8wLeCOoT

code is here:-

html



<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
<div ng-repeat="item in items" ng-class="{sel: item.Item == selected}">
<label>Item No. {{item.Item}}</lablel> |
<label>{{item.Description}}</label> |
<button ng-click="onClick(item.Item);" class="btn btn-primary">
{{item.Item == selected ? 'Hide' : 'Show'}}
</button>
</div>
<br />
<br />
<div ng-switch="moduleState">
<div ng-switch-when="details">
These are your details:-
Item {{selected}} is selected
</div>
</body>
</html>


app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
$scope.items = [
{
Item: 1,
Description: 'This is item 1'
},
{
Item: 2,
Description: 'This is item 2'
},
{
Item: 3,
Description: 'This is item 3'
}
];

$scope.onClick = function (item) {
$scope.selected = item;
$scope.moduleState = 'details';
};
});


Once one of the buttons is selected how do I deselect it again?

Answer
$scope.onClick = function(item) {
  if ($scope.selected === item) {
    $scope.selected = null;
  }
  else {
    $scope.selected = item;
  }
};

And in the view:

<div ng-repeat="item in items" ng-class="{sel: item.Item == selected}">
  <label>Item No. {{item.Item}}</lablel> |
  <label>{{item.Description}}</label> |
  <button ng-click="onClick(item.Item);" class="btn btn-primary">
    {{item.Item == selected ? 'Hide' : 'Show'}}
  </button>
</div>

<br />
<br />

<div ng-if="selected">
  These are your details:-
  Item {{ selected }} is selected
</div>