【问题标题】:AngularJs best way to repeat html code with the ability to hide itAngularJs 重复 html 代码并能够隐藏它的最佳方法
【发布时间】:2017-11-09 11:56:53
【问题描述】:

AngularJs 的新手。在我的 html 中,我有两个表格行,它们一遍又一遍地重复和填充。如果我单击第一行上的按钮,我需要第二行出现/消失。这是我的目标中的一些伪的、不完整的角度

<tr ng-repeat-start="item in collection" id="firstTr">
  <td>
    <button type="button" ng-click="toggleTheSecondTr">
        toggle visibility for second tr
    </button>
  <td>
  <td>
    {{item.value}}
  </td>
</tr>
<tr ng-Hide="the above button got clicked" id="secondTr" ng-repeat-end>
  <td>
     something goes here, there can be many td's
  </td>
  <td>
    {{item.someOtherValue}}
  </td>
</tr>

这段代码会一遍又一遍地重复。但是,我需要以一种方式绑定按钮,当单击按钮时,第二行被隐藏,或者如果再次单击,它会再次显示,几乎就像一个拨动开关。我不知道该怎么做。我可以使用后面的 typescript 代码中的变量来跟踪它(我们使用的是 typescript,而不是 js),但我无法保证这两行将重复多少次,因此不知道要跟踪多少变量。关于如何解决我的问题的建议?

编辑:例如,我本质上希望功能与此页面中的表格非常相似,但我的行数是可变的,可以是一个或多个https://www.visualstudio.com/vs/compare/

【问题讨论】:

  • 注意小写ng-hide 而不是ng-HidetoggleTheSecondTr 需要使用toggleTheSecondTr() 进行函数调用,并且您需要该函数存在于控制器的$scope 中。希望对您有所帮助。
  • collection 中的每个 item 是否有一个 id 或唯一值?如果是这样,您可以使用地图来跟踪显示/隐藏的内容。
  • 是的,集合中的项目是独一无二的,它们取自具有大约 30-40 个不同属性的 json
  • 像本页顶部这样的表格基本上是我想要完成的工作,单击 + 按钮可取消隐藏表格行以显示更多信息 visualstudio.com/vs/compare
  • 但在我的情况下,行数可以是 1 到 50 到 500 之间的任何位置,它是动态填充的

标签: html angularjs typescript


【解决方案1】:

解决方案如下:
在集合的每个对象中使用布尔变量来显示或隐藏其各自部分中的第二个 &lt;tr&gt;

angular.module('MyApp', [])
  .controller('MyController', ['$scope', function($scope){
    $scope.collection = [];
    $scope.collection.push({value:'Test', someOtherValue:'UAT', hideSecondRow: false});
    $scope.collection.push({value:'Dev', someOtherValue:'Development', hideSecondRow: true});
    $scope.collection.push({value:'Prod', someOtherValue:'PreProd', hideSecondRow: false});
    $scope.toggleTheSecondTr = function(index){
      $scope.collection[index].hideSecondRow = !$scope.collection[index].hideSecondRow;
    }
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
  <div ng-controller="MyController">
    <table>
      <tr ng-repeat-start="item in collection" id="firstTr">
        <td>
          <button type="button" ng-click="toggleTheSecondTr($index)">
              toggle visibility for second tr
          </button>
        <td>
        <td>
          {{item.value}}
        </td>
      </tr>
      <tr ng-hide="item.hideSecondRow" id="secondTr" ng-repeat-end>
        <td>
           something goes here, there can be many td's
        </td>
        <td>
          {{item.someOtherValue}}
        </td>
      </tr>
    </table>
  </div>
</div>

【讨论】:

  • 嗨,Yatin,感谢您的回答。我测试了该代码,但问题在于大于一个的集合,每个按钮每隔一秒隐藏一次,而不是按钮正下方的那个。我希望该按钮仅切换其正下方的 tr 。有关如何更改控制器或 html 代码以实现大于 1 的此功能的任何建议?
  • @pdaniels0013 给你,伙计;我已经更新了解决方案以在每个对象内包含一个布尔值,可以对其进行修改以显示/隐藏其各自部分中的第二行。让我知道这个是否适合您。
猜你喜欢
  • 2022-07-27
  • 2014-01-01
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 2014-07-26
相关资源
最近更新 更多