繁体   English   中英

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

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

我的ng-repeat列表中的每个项目都有一个按钮。 默认情况下隐藏按钮,我想在用户选择列表项时显示按钮,并在用户选择另一个列表项时隐藏按钮。 我无法使其工作,当用户选择列表项时,按钮保持隐藏状态。

以下是我到目前为止所尝试的相关代码。

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代码:

$scope.selectthing = function(idx) {

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

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

我的问题是:如何在用户选择列表项时显示按钮,并在用户另一个列表项时隐藏按钮?

你几乎得到了它:

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

plnkr

你正在混合Angular和jQuery,这是地狱的滑坡:)(好吧,警告:指令,但这是一个不同的故事)。 如果你发现自己要在你的控制器中编写jQuery,那么警钟应该响起你正在打破MVC分离并错过更简单的东西。

这里的诀窍是让你的ng-show以当前正在呈现的项目是否是选定的项目为条件。 要检测到这一点,请在所选索引的范围内进行记录。 像这样......

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控制器:

$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