repeat指令及Ajax的应用实例分析

<element ng-repeat="expression"></element>

说明:experssion表达式定义了如何循环集合。常用的如:x in records

下面通过一个例子,来说明ng-repeat如何绘制一个表格:

<div ng-app='mainApp' ng-controller='studentController'> <table> <tr> <td>姓</td> <td><input type="text" ng-model='student.firstName'></td> </tr> <tr> <td>名</td> <td><input type="text" ng-model='student.lastName'></td> </tr> <tr> <td>名字</td> <td>{{student.fullName()}}</td> </tr> <tr> <td>科目</td> <td> <table> <tr> <th>名字</th> <th>标记</th> </tr> <tr ng-repeat='sub in student.subjects'> <td>{{sub.name}}</td> <td>{{sub.marks}}</td> </tr> </table> </td> </tr> </table> </div>

表可以使用CSS样式设置样式。

<style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style>

利用angularjs的ng-repeat指令绘制表格:

<script> var mainApp=angular.module('mainApp',[]); //定义一个名为mainApp的模块 mainApp.controller('studentController',function($scope){ $scope.student={ firstName:'聂', lastName:'鹏飞', subjects:[ {name:'物理',marks:73}, {name:'化学',marks:90}, {name:'数学',marks:68}, {name:'英文',marks:85}, {name:'生物',marks:77}, ], fullName:function(){ var studentObject; studentObject = $scope.student; return studentObject.firstName+' '+studentObject.lastName; } }; }); </script>

效果:

repeat指令及Ajax的应用实例分析

上面例子表格中展示的数据也可以通过ajax请求从服务器中获取,然后利用ng-repeat指令插入到页面中,具体实现见下面代码:

<html> <head> <title>Angular JS Controller</title> <script src="https://www.jb51.net/angularjs/angular-1.3.0/angular.min.js"></script> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS 表格应用示例</h2> <div ng-app='mainApp' ng-controller='studentController'> <table> <tr> <td>姓</td> <td><input type="text" ng-model='student.firstName'></td> </tr> <tr> <td>名</td> <td><input type="text" ng-model='student.lastName'></td> </tr> <tr> <td>名字</td> <td>{{student.fullName()}}</td> </tr> <tr> <td>科目</td> <td> <table> <tr> <th>名字</th> <th>标记</th> </tr> <tr ng-repeat='sub in student.subjects'> <td>{{sub.name}}</td> <td>{{sub.marks}}</td> </tr> </table> </td> </tr> </table> </div> <script> var mainApp=angular.module('mainApp',[]); mainApp.controller('studentController',function($scope,$http){ $scope.student={ firstName:'聂', lastName:'鹏飞', fullName:function(){ var studentObject; studentObject = $scope.student; return studentObject.firstName+' '+studentObject.lastName; }, }; var url="data.txt"; $http.post(url).success(function(response){ $scope.student.subjects=response; }) }); </script> </body> </html>

说明:需要放在服务器环境中运行

更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《AngularJS指令操作技巧总结》、《AngularJS入门与进阶教程》及《AngularJS MVC架构总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyfzxj.html