Show and hide button in ng-repeat list

I have a button on each ng-repeat list item. The button is hidden by default, I want to show the button when the user selects a list item and hides the button when the user selects another list item. I can't get this to work, the button remains hidden when the user selects a list item.

Here is the relevant bit of code from what I've tried so far.

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>

      

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 to get the button to show when the user selects a list item and hides the button when the user has another list item?

+3


source to share


2 answers


You 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

+4


source


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

The trick here is to make your ng-show conditional if the current displayable is selected. To discover this, take a note in your area of ​​the selected index. So ...

HTML representation:



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

      

+2


source







All Articles