简体   繁体   中英

Show and hide button in ng-repeat list

I have a button in every item of my ng-repeat list. The button is hidden by default, I want to show the button when the user selects the list item and hide the button when the user selects another list item. I am not able to get this to work, the button stays hidden when the user selects the list item.

Here are the relevant bit of code from what I have tried so far.

The HTML:

<ul ng-repeat="thing in things" role="presentation" id="thing-details" ng-click="selectthing($index)" >
   <li>
        <p>Name: {{thing.name}} </p>

        <button class="btn btn-block" ng-show="false" id="thing-delete" >Delete</button>
   </li>
</ul>

The JS code:

$scope.selectthing = function(idx) {

      $(this).find('ul.btn').show();  // this is not working

      .
      .
      .
      // do some awesome stuff with the selected thing.
}

My question is: How do I get the button to show when the user selects the list item and hide the button when the user another list item ?

You've almost got it:

<ul ng-repeat="thing in things">
  <li>
    <p ng-click="$parent.selectedIndex = $index">Name: {{thing.name}}</p>

    <button class="btn btn-block" 
            ng-show="$parent.selectedIndex == $index">Delete</button>
  </li>
</ul>

See plnkr

You are mixing Angular and jQuery, and that's the slippery slope to Hell :) (ok, caveat: directives, but that's a different story). If you find yourself about to write jQuery in your controller then alarm bells should ring that you are breaking the MVC separation and missing something simpler.

The trick here is to make your ng-show conditional on whether the current item being rendered is the selected one. To detect that, make a note in your scope of the selected index. Like so ...

HTML view:

<ul ng-repeat="thing in things" role="presentation" id="thing-details" ng-click="selectthing($index)" >
    <li>
        <p>Name: {{thing.name}} </p>

        <button class="btn btn-block" ng-show="$index===selectedIndex" id="thing-delete" >Delete</button>
    </li>
</ul>

JS controller:

$scope.selectedIndex = -1;
$scope.selectthing = function(idx) {

    $scope.selectedIndex = idx;

    .
    .
    .
    // do some awesome stuff with the selected thing.
}

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