Angular.js中用ng-repeat-start实现自定义显示?

Angular.js中用ng-repeat-start实现自定义显示


汪汪一只猫
浏览 933回答 1
1回答

一只甜甜圈

前言&nbsp;众所周知AngularJS 中可以使用 ng-repeat 显示列表数据,这对大家来说应该都不陌生了, 用起来很简单, 也很方便, 比如要显示一个产品表格, Controller 的 Javascript 代码如下:&nbsp; &nbsp; &nbsp;angular.module('app', []) &nbsp;.controller('MyController', MyController); &nbsp; &nbsp;MyController.$inject = ['$scope']; &nbsp;function MyController($scope) { &nbsp; // 要显示的产品列表数据; &nbsp; $scope.products = [ &nbsp; &nbsp;{ &nbsp; &nbsp; id: 1, &nbsp; &nbsp; name: 'Product 1', &nbsp; &nbsp; description: 'Product 1 description.' &nbsp; &nbsp;}, &nbsp; &nbsp;{ &nbsp; &nbsp; id: 2, &nbsp; &nbsp; name: 'Product 3', &nbsp; &nbsp; description: 'Product 2 description.' &nbsp; &nbsp;}, &nbsp; &nbsp;{ &nbsp; &nbsp; id: 3, &nbsp; &nbsp; name: 'Product 3', &nbsp; &nbsp; description: 'Product 3 description.' &nbsp; &nbsp;} &nbsp; ]; &nbsp;} &nbsp; &nbsp;对应的 HTML 视图代码如下:&nbsp; &nbsp; &nbsp; <table class="table"> &nbsp; &nbsp;<tr> &nbsp; &nbsp; <th>id</th> &nbsp; &nbsp; <th>name</th> &nbsp; &nbsp; <th>description</th> &nbsp; &nbsp; <th>action</th> &nbsp; &nbsp;</tr> &nbsp; &nbsp;<tr ng-repeat="p in products"> &nbsp; &nbsp; <td></td> &nbsp; &nbsp; <td></td> &nbsp; &nbsp; <td></td> &nbsp; &nbsp; <td><a href="#">Buy</a></td> &nbsp; &nbsp;</tr> &nbsp; </table> &nbsp; &nbsp;运行效果图:&nbsp;&nbsp;可是如果全部页面都是每个产品占一行来显示, 未免太枯燥了, 比如用户希望这样子自定义显示:&nbsp;&nbsp;每个产品占表格的两行, 这样的效果用 ng-repeat 就没办法实现了。 不过 AngularJS 提供了 ng-repeat-start 和 ng-repeat-end 来实现上面的需求, ng-repeat-start 和 ng-repeat-end 的语法如下:&nbsp; &nbsp; &nbsp; <header ng-repeat-start="item in items"> &nbsp; &nbsp;Header &nbsp; &nbsp;</header> &nbsp; <div class="body"> &nbsp; &nbsp;Body &nbsp; &nbsp;</div> &nbsp; <footer ng-repeat-end> &nbsp; &nbsp;Footer &nbsp; &nbsp;</footer> &nbsp; &nbsp;假设提供了 ['A','B'] 两个产品, 则生成的 HTML 结果如下:&nbsp; &nbsp; &nbsp; <header> &nbsp; &nbsp;Header A &nbsp; </header> &nbsp; <div class="body"> &nbsp; &nbsp;Body A &nbsp; </div> &nbsp; <footer> &nbsp; &nbsp;Footer A &nbsp; </footer> &nbsp; <header> &nbsp; &nbsp;Header B &nbsp; </header> &nbsp; <div class="body"> &nbsp; &nbsp;Body B &nbsp; </div> &nbsp; <footer> &nbsp; &nbsp;Footer B &nbsp; </footer> &nbsp; &nbsp;了解了 ng-repeat-start 和 ng-repeat-end 的用法之后, 上面要求的界面就很容易实现了, 代码如下:&nbsp; &nbsp; &nbsp; <table class="table table-bordered"> &nbsp; &nbsp;<tr ng-repeat-start="p in products"> &nbsp; &nbsp; <td></td> &nbsp; &nbsp; <td rowspan="2"><a href="#">Buy</a></td> &nbsp; &nbsp;</tr> &nbsp; &nbsp;<tr ng-repeat-end> &nbsp; &nbsp; <td></td> &nbsp; &nbsp;</tr> &nbsp; </table> &nbsp; &nbsp;总结&nbsp;以上就是Angular.js中利用ng-repeat-start实现自定义显示的全部内容,希望本文的内容对大家学习或者使用Angular.js能有所帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS