inoic请求数据与loading的显示隐藏

本文示例了如何在AngularJS和Ionic框架中处理数据请求,并结合使用$ionicLoading服务来显示和隐藏加载指示器。通过在$httpProvider拦截器中监听请求和响应事件,动态控制loading的展示和隐藏,实现更好的用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值