在AngularJS中,有許多的service供您注入使用。而官方內建的service,開頭都加了$字號,例如$http、$filter...,當然我們也能自訂service(不得以$字號開頭,怕跟內建的互衝),
供不同的controller使用,已達到reuse的目的。而我們能把提取後端資料的部分做成一service,如以下筆記:
services.js :
angular.module('myApp', ['ngResource']). //將ngResource module加入自訂的application
factory('myService', function ($resource) { //create service
return $resource('WebService.asmx/getData', {}, {
//格式參考http://docs.angularjs.org/api/ngResource.$resource
'query': { method: 'POST',isArray:true }
})
});
controllers.js:
//自訂的service 注入到PhoneListCtrl controller中
function PhoneListCtrl($scope, myService) {
//myService.query()取得service中的資料
$scope.phones = myService.query();
}
Default.aspx:
<htmlng-app="myApp">
<head>
<title>Test Angular</title>
<scriptsrc="Scripts/angular.js"></script>
<!--匯入angular-resource.js取得ngResource module -->
<scriptsrc="Scripts/angular-resource.js"></script>
<scriptsrc="Scripts/services.js"></script>
<scriptsrc="Scripts/controllers.js"></script>
<styletype="text/css">
img{width:10%;}
li{border:1pxsolidgray;margin:5px; list-style-type:none}
</style>
</head>
<body>
<divng-controller="PhoneListCtrl">
<ul>
<ling-repeat="phone in phones">
Name:<div>{{phone.name}}</div>
<imgng-src="../{{phone.imageUrl}}"/><br/>
Snippet:<div>{{phone.snippet}}</div>
</li>
</ul>
</div>
</body>
</html>
WebService.asmx:
publicclassWebService : System.Web.Services.WebService {
[WebMethod]
publicvoid getData() {
List<Phone> list = newList<Phone>();
Phone p1 = newPhone()
{
age = 0,
id = "motorola-xoom-with-wi-fi",
imageUrl = "img/phones/motorola-xoom-with-wi-fi.0.jpg",
name = "Motorola XOOM\u2122 with Wi-Fi",
snippet = @"The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM
with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb)."
};
Phone p2 = newPhone()
{
age = 1,
id = "motorola-xoom",
imageUrl = "img/phones/motorola-xoom.0.jpg",
name = "MOTOROLA XOOM\u2122",
snippet = @"The Next, Next Generation\n\nExperience the future with MOTOROLA XOOM,
the world's first tablet powered by Android 3.0 (Honeycomb)."
};
Phone p3 = newPhone()
{
age = 2,
id = "motorola-atrix-4g",
imageUrl = "img/phones/motorola-atrix-4g.0.jpg",
name = "MOTOROLA ATRIX\u2122 4G",
snippet = @"MOTOROLA ATRIX 4G the world's most powerful smartphone."
};
list.Add(p1);
list.Add(p2);
list.Add(p3);
JavaScriptSerializer js = newJavaScriptSerializer();
string json = js.Serialize(list);
this.Context.Response.ContentType = "application/json";
this.Context.Response.Write( json);
}
}
截圖: