AngularJS-常用服務
Angular 內建了很多服務,例如$location服務,用來和瀏覽器的地址欄進行互動;$root服務,用來根據URL地址的變換切換視圖;還有$http服務,用來和伺服器進行互動。
$routeProvider
使用 $routeProvider綁定路由與視圖。
我們可以利用路由服務定義這樣一種東西:對於瀏覽器所指向的特定URL,Angular將會載入並顯示一個模板,並執行個體化一個控制器來為模板提供內容。
切換視圖的原理:Angular發起的請求:
XHR:SmlHttpRequest,本質是Ajax。
$http$http.get(url) : get方式擷取url返回。
得到的JSON資料
| 名 |
城市 |
國家 |
| {{ x.Name }} |
{{ x.City}} |
{{ x.Country }} |
<script> function customersController($scope,$http) { $http.get("http://www.w3cschool.cc/try/angularjs/data/Customers_JSON.php")//這個http請求會拿到純文字返回,裡面是json內容。 .success(function(response) {$scope.names = response;});//response就是json格式的資料,相當於把json還原序列化為了js對象。 } </script> <script src="http://apps.bdimg.com/libs/angular.js/1.2.15/angular.min.js"></script>
$http拿到的json內容見下:
[ { "Name" : "Alfreds Futterkiste", "City" : "Berlin", "Country" : "Germany" }, { "Name" : "Berglunds snabbköp", "City" : "Luleå", "Country" : "Sweden" }, { "Name" : "Centro comercial Moctezuma", "City" : "México D.F.", "Country" : "Mexico" }, { "Name" : "Ernst Handel", "City" : "Graz", "Country" : "Austria" }, { "Name" : "FISSA Fabrica Inter. Salchichas S.A.", "City" : "Madrid", "Country" : "Spain" }, { "Name" : "Galería del gastrónomo", "City" : "Barcelona", "Country" : "Spain" }, { "Name" : "Island Trading", "City" : "Cowes", "Country" : "UK" }, { "Name" : "Königlich Essen", "City" : "Brandenburg", "Country" : "Germany" }, { "Name" : "Laughing Bacchus Wine Cellars", "City" : "Vancouver", "Country" : "Canada" }, { "Name" : "Magazzini Alimentari Riuniti", "City" : "Bergamo", "Country" : "Italy" }, { "Name" : "North/South", "City" : "London", "Country" : "UK" }, { "Name" : "Paris spécialités", "City" : "Paris", "Country" : "France" }, { "Name" : "Rattlesnake Canyon Grocery", "City" : "Albuquerque", "Country" : "USA" }, { "Name" : "Simons bistro", "City" : "København", "Country" : "Denmark" }, { "Name" : "The Big Cheese", "City" : "Portland", "Country" : "USA" }, { "Name" : "Vaffeljernet", "City" : "Århus", "Country" : "Denmark" }, { "Name" : "Wolski Zajazd", "City" : "Warszawa", "Country" : "Poland" } ]
網頁效果