Question

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.

Was it helpful?

Solution 2

Most attributes in Angular are either evaluated or interpolated. Evaluation is like a restricted form of eval(), interpolation is when the double curly braces get filled in. It looks like you're expecting the ng-show to be interpolated then evaluated, but none of the built-in directives do this. They do one or the other but not both. For ng-show specifically it just does evaluation, so your curly braces pass through literally. This would be an invalid expression.

My suggestion is this: Since ng-repeat creates a new scope for each repeated item, you can just do this:

<div class="row" ng-repeat="item in items" ng-cloak>
  <div ng-show="!hide" class="ng-hide">
  <button ng-click="hide = true">Remove</button>
</div>

Of course, why keep a bunch of hidden items around. Why not have ng-click="remove(item)" and a remove function that removes from items? Then the ng-repeat updates naturally.

$scope.remove = function(item) {
  var index = this.items.indexOf(item);
  if (index != -1) {
    this.items.splice(index);
  }
};

Or something like that.

OTHER TIPS

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

You don't need to use {{ }} in angular's attributes. It will automatically evaluate your scopes.

<div class="row" ng-repeat="item in items" ng-cloak>
    <div ng-show="'unique' + $index" class="ng-hide">
    <button ng-click="remove('unique' + $index)">Remove</button>
  </div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top