简体   繁体   中英

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)
}

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 !

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM