AngularJS 的 ajax- $http

用 AngularJS 來做 ajax 可以比用 jQuery 輕鬆愉快很多。


基本用法在 html 部分一樣用 ng-repeat 把回傳的 json 塞到 DOM 裡面就好了。
  1. <div ng-controller="MyController">  
  2.     <ul>  
  3.         <li data-ng-repeat="school in school">{{school.name}}</li>  
  4.     </ul>  
  5. </div>  

javascript 處理起來跟 jquery 有點像,只是不用再這邊處理 DOM 了,有需要再把回傳的 json 格式整理一下就好了。

  1. function MyController($scope, $http){   
  2.     $http({   
  3.         method: 'GET',   
  4.         url: 'school.json'  
  5.     }).success(function(data, status, headers, config) {   
  6.         $scope.school=data;   
  7.            
  8.     }).error(function(data, status, headers, config) {   
  9.            
  10.     });   
  11. }  

留言