buydadip
buydadip

Reputation: 9437

ng-click to affect only the element it is inside

I am using ng-repeat to generate some elements...

<div class="form-block" ng-repeat="form in formblock | filter:dateFilter">

    <div ng-click="showResults()" ng-if="repeat == true" class="drop">{{ form.form_name }} <span class="caret"></span></div>

    <div ng-show="results" class="formURL">{{ form.url }}</div>
    <div ng-show="results" class="formCount">{{ form.count }}</div>
    <div ng-show="results" class="formSubmit">{{ form.submit }}</div>

</div>

As you can see, ng-click="showResults()" toggles the display of the other elements. The problem is, I only want the ng-click to toggle the elements inside the same container, not toggle all elements.

In short, I only want the click event to affect the elements in the same container that the function is called, how can I do this?

this is showResults in my controller...

$scope.showResults = function(){
  return ($scope.results ? $scope.results=false : $scope.results=true)
}

Upvotes: 1

Views: 573

Answers (2)

Ven
Ven

Reputation: 19040

ng-repeat provides you with a special variable (unless you already have an identfier): $index.

Using this, you can store (instead of a single boolean value) an object $index => toggleState in your angular code:

$scope.hiddenHeroes = {};

$scope.toggleHero = function (idx) {
    $scope.hiddenHeroes[idx] = !$scope.hiddenHeroes[idx];
}

And in your HTML:

<div ng-repeat="hero in heroes">
  <div class="hero" ng-hide="hiddenHeroes[$index]">
  <h1>
  {{hero}}
  </h1>
  All you want to know about {{hero}}!
  <br />
  </div>
  <a ng-click="toggleHero($index)">Toggle {{hero}}</a>
</div>

See it live on jsfiddle.net!

Upvotes: 2

Dario
Dario

Reputation: 6280

You can use $index to index item/containers and show the corresponding results:

<div ng-click="showResults($index)" ng-if="repeat == true" class="drop">{{ form.form_name }} <span class="caret"></span></div>
<div ng-show="results[$index]" class="formURL">{{ form.url }}</div>
<div ng-show="results[$index]" class="formCount">{{ form.count }}</div>
<div ng-show="results[$index]" class="formSubmit">{{ form.submit }}</div>

And your function

$scope.showResults = function(index){
  return ($scope.results[index] ? $scope.results[index]=false : $scope.results[index]=true)
}

Upvotes: 0

Related Questions