简体   繁体   English

在ng-repeat列表中显示和隐藏按钮

[英]Show and hide button in ng-repeat list

I have a button in every item of my ng-repeat list. 我的ng-repeat列表中的每个项目都有一个按钮。 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: 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: JS代码:

$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 plnkr

You are mixing Angular and jQuery, and that's the slippery slope to Hell :) (ok, caveat: directives, but that's a different story). 你正在混合Angular和jQuery,这是地狱的滑坡:)(好吧,警告:指令,但这是一个不同的故事)。 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. 如果你发现自己要在你的控制器中编写jQuery,那么警钟应该响起你正在打破MVC分离并错过更简单的东西。

The trick here is to make your ng-show conditional on whether the current item being rendered is the selected one. 这里的诀窍是让你的ng-show以当前正在呈现的项目是否是选定的项目为条件。 To detect that, make a note in your scope of the selected index. 要检测到这一点,请在所选索引的范围内进行记录。 Like so ... 像这样......

HTML view: 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="$index===selectedIndex" id="thing-delete" >Delete</button>
    </li>
</ul>

JS controller: JS控制器:

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

    $scope.selectedIndex = idx;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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