AngularJS如何实现列表行按钮点击通过ng-show展示对应单条详情数据
解决方法
你需要对现有代码做3处调整即可实现需求:
- 控制器中新增变量存储当前选中的行数据,同时修改
viewMore方法接收当前点击的行对象 - 按钮点击事件中传入当前循环到的行对象
- 底部详情区直接渲染选中的行数据,不需要再遍历全量列表
修改后的JS代码
import angular from 'angular'; angular.module('plunker', []).controller('MainCtrl', function($scope) { $scope.userInfo = [ {"name":"John", "hobby":"fishing", "ID":"123"}, {"name":"Bob", "hobby":"Golf", "ID":"199"}, {"name":"Jerry", "hobby":"Football", "ID":"aAAa"} ]; // 存储当前选中的行数据 $scope.selectedRow = null; $scope.viewMore = function(row){ $scope.showDiv = true; $scope.selectedRow = row; } });
修改后的HTML代码
<div ng-controller="MainCtrl"> <h1>从列表中选择对应信息</h1><br> <table> <tr> <th>姓名</th> <th>ID</th> </tr> <tr ng-repeat = "x in userInfo"> <td>{{x.name}}</td> <td>{{x.ID}}</td> <!-- 点击时传入当前行对象 --> <td><button ng-click = "viewMore(x)">查看详情</button></td> </tr> </table><br><br> <div ng-show = "showDiv && selectedRow"> <h3>选中的信息</h3> <table> <tr> <th>姓名(选中)</th> <th>爱好(选中)</th> <th>ID(选中)</th> </tr> <tr> <!-- 直接渲染选中行的字段即可,不需要遍历 --> <td>{{selectedRow.name}}</td> <td>{{selectedRow.hobby}}</td> <td>{{selectedRow.ID}}</td> </tr> </table><br><br> </div> </div>
如果一定要按照你最初的思路用ID筛选实现,也可以把底部的ng-repeat改成x in userInfo | filter:{ID: selectedId}:true,同时在控制器里存储选中的ID而不是整行对象即可,两种方案都可以实现需求。
内容的提问来源于stack exchange,提问作者versb
相关产品推荐
相关产品推荐

