
function studentController($scope,$http) {
var url="data.txt"
$http.get(url).success( function(response) {
$scope.students = response
})
}
在这里,data.txt中包含的学生记录。 $http服务使Ajax调用和设置针对其学生的属性。 “学生”模型可以用来用来绘制 HTML 表格。
例子
data.txt[
{
"Name" : "Mahesh Parashar",
"RollNo" : 101,
"Percentage" : "80%"
},
{
"Name" : "Dinkar Kad",
"RollNo" : 201,
"Percentage" : "70%"
},
{
"Name" : "Robert",
"RollNo" : 191,
"Percentage" : "75%"
},
{
"Name" : "Julian Joe",
"RollNo" : 111,
"Percentage" : "77%"
}
]
testAngularJS.html<html>
<head>
<title>Angular JS Includes</title>
<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 Sample Application</h2>
<div ng-app="" ng-controller="studentController">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat="student in students">
<td>{{ student.Name }}</td>
<td>{{ student.RollNo }}</td>
<td>{{ student.Percentage }}</td>
</tr>
</table>
</div>
<script>
function studentController($scope,$http) {
var url="data.txt"
$http.get(url).success( function(response) {
$scope.students = response
})
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>
输出
要运行这个例子,需要部署textAngularJS.html,data.txt到一个网络服务器。使用URL在Web浏览器中打开textAngularJS.html请求服务器。看到结果如下:
angular1 自带 $resource 服务 。你可以自定义个 服务(factory)用 $resource 请求接口,然后把刚才自定义的服务注入到你要用到的请求的 Controller 里面。如果是为了对请求、响应,请求错误及响应错误做统一处理,那就需要使用拦截器(Interceptors)了。可以使用factory创造自定义的拦截器,然后把它们添加到$httpProvider.interceptors(是一个数组)之中,如此一来这些拦截器就好像中间件那样的对每一此请求都做出统一的处理。欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)