Angular JS 学习之Http
1.$http是AngularJS中的一个核心服务,用于读取远程服务器的数据;
2.读取JSON文件:
**JSON文件如下:
{
"sites":[
{
"Name":"菜鸟教程",
"Url":"www.runoob.com",
"Country":"CN",},
{
"Name":"Google",
"Url":"www.google.com",
"Country":"USA"},
{
"Name":"Facebook",
"Url":"www.facebook.com",
"Country":"USA"},
{
"Name":"微博",
"Url":"www.weibo.com",
"Country":"CN"}
]
}
**$http.get(url)是用于读取服务器数据的函数;
<div ng-app="myApp" ng-controller="siteCtrl" >
<ul>
<li ng-repeat="x in names">
{{x.Name+' ,'+x.Country}}
</li>
</ul>
</div>
<script>
var app=angular.module('myApp',[]);
app.controller('siteCtrl',function($scope,$http){
$http.get("http://www.runoob.com/try/angularjs/data/sites.php").success(function(response){$scope.names=response.sites;});
});
</script>
**以上代码的get请求是本站的服务器;
**AngularJS应用通过ng-app定义,应用于<div>中执行;
**ng-controller指令设置了controller对象名;
**函数customerController是一个标准的javaScript对象构造器;
**控制器对象有一个属性:$scope.names;
**$http.get()从web服务器上读取静态JSON数据;
**服务器文件为:http://www.runoob.com/try/angularjs/data/sites.php;
**当服务端载入JSON数据时,$scope.names变为一个数组;