本文实例讲述了AngularJSng-repeat指令及Ajax的应用。分享给大家供大家参考,具体如下:ng-repea
本文实例讲述了AngularJS ng-repeat指令及Ajax的应用。分享给大家供大家参考,具体如下:
ng-repeat 指令用于循环输出指定次数的 HTML 元素。集合必须是数组或对象。
定义:
<element ng-repeat="expression"></element>
说明:experssion表达式定义了如何循环集合。常用的如:x in records
下面通过一个例子,来说明ng-repeat如何绘制一个表格:
<div ng-app='mainApp' ng-controller='studentController'>
<table border="0">
<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>
效果:
上面例子表格中展示的数据也可以通过ajax请求从服务器中获取,然后利用ng-repeat指令插入到页面中,具体实现见下面代码:
<html>
<head>
<title>Angular JS Controller</title>
<script src="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 border="0">
<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 ng-repeat指令 Ajax