1. 程式人生 > >inoic請求資料與loading的顯示隱藏

inoic請求資料與loading的顯示隱藏

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="utf-8">
    <meta name="viewport" content="width=device-width, maximum-scale=1.0, user-scalable=no" /> 
    <title>無標題文件</title>
     <link href="../lib/ionic/css/ionic.min.css" rel="stylesheet">
   <script src="../lib/ionic/js/ionic.bundle.min.js"></script>

</head>

<body ng-app="myApp">
<div ng-controller="firstController">
    <ul class="list">
        <li class="item" ng-repeat="item in items">{{item}}</li>
    </ul>
</div>
<script>


var app = angular.module('myApp', ['ionic'])

app.config(function($httpProvider) {
  $httpProvider.interceptors.push(function($rootScope) {//$rootScope全域性變數
    return {
      request: function(config) {//請求資料,顯示loading
        $rootScope.$broadcast('loading:show')//$broadcast廣播給所有控制器。
        return config
      },
      response: function(response) {//響應資料之後,關閉loading
        $rootScope.$broadcast('loading:hide')
        return response
      }
    }
  })
})
app.service("service01",function($http){//service自定義服務,所有邏輯處理資料都放裡面。
    //可以用當前的this配置邏輯shu'j
    var _name='';

    this.setName=function(name){
        _name=name;
    };
    this.getName=function(){
        return _name;
    };
    this.getData = function(){//控制器controller重新整理關閉會丟失資料。
        var url = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSON_CALLBACK"
        return $http.jsonp(url,{cache:true});//可以從快取裡呼叫資料,減少請求的次數
    }
})
app.run(function($rootScope, $ionicLoading) {
  $rootScope.$on('loading:show', function() {//$on繫結loading的動態狀態
    $ionicLoading.show({template: '你好嗎'})//show裡面可以定製loading介面
     /*show()方法的 options 引數是一個 JSON 物件,可以包含如下欄位:
        template - 模板字串
        templateUrl - 內聯模板的 Url
        scope - 要繫結的作用域物件
        noBackdrop - 是否隱藏背景幕
        hideOnStateChange - 當切換到新的檢視時,是否隱藏載入指示器
        delay - 顯示載入指示器之前要延遲的時間,以毫秒為單位,預設為 0,即不延遲 duration - 載入指示器持續時間,以毫秒為單位。時間到後載入指示器自 動隱藏。預設
        情況下, 載入指示器保持顯示狀態,知道顯示的呼叫 hide()方法
          })
        */
  })

  $rootScope.$on('loading:hide', function() {
    $ionicLoading.hide()
  })
})

app.controller('firstController', function($http, $ionicLoading,$scope,service01) {
   service01.getData().success(function(data){
       console.log(data);
       $scope.items = [];
       for(var i=0; i<15; i++){
            $scope.items.push(data.result[i].title);
           //            $scope.items.push([data.result[i].title].join(""));
       }
      
   }).error(function(){
       alert("false")
   })
})
</script>
</body>
</html>