Programmatically create an ng-show value in ng-repeat

Apples picture Apples · Aug 21, 2013 · Viewed 9.3k times · Source

I have the following:

  <div class="row" ng-repeat="item in items " ng-cloak>
    <div ng-show="unique{{$index}}" class="ng-hide">
    <button ng-click="remove('{{$index}})">Remove</button>
  </div>

I want to create a unique value for every div item repeated,like so:

<div ng-show="unique1" class="ng-hide">
  <button ng-click="remove('unique1')">Remove</button>
<div ng-show="unique2" class="ng-hide">
  <button ng-click="remove('unique2')">Remove</button>

so that in my controller I can have an action, in this case remove(), that will toggle that attribute.

scope.remove = function(uniqueAttribute) {
  $scope[uniqueAttribute] = false;

}

I was able to generate the html using $index but that code does not work and I am sure not sure how to go about accomplishing this.

Answer

zs2020 picture zs2020 · Aug 21, 2013

You can add a new field called show to each object and then you can eliminate all logic relating to the $index.

<div ng-app ng-controller="Ctrl">
    <div class="row" ng-repeat="item in items" ng-cloak>
        <div ng-show="item.show">
            <button ng-click="remove(item)">Remove</button>
        </div>
    </div>
</div>

function Ctrl($scope) {
    $scope.items = [{
        item1: 1,
        show: true
    }, {
        item1: 2,
        show: true
    }, {
        item1: 3,
        show: false
    }];

    $scope.remove = function (item) {
        item.show = false;
    }
}

DEMO