简单实现angularjs遮罩过渡加载

本文介绍如何在AngularJS中实现页面加载时的遮罩效果,通过自定义HTTP拦截器和遮罩组件来提升用户体验。适用于AngularJS 1.2.6及jQuery 1.9环境。

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

前言
很多情况下angularjs 加载页面时,会显示‘{{}}’ 等,带来页面美观性的问题。所以这个时候我们要用到遮罩,也就是页面加载时过渡.在做之前,可以先参考下angularjs 拦截器的API文档 点击查看

angularjs遮罩过渡加载实现步骤

开发的环境:
angularjs1.2.6 jquery1.9,主要是这几个js工具包
可以兼容ie8及以上系统 本人测试过无毛病

1. $http服务添加自定义拦截器

var apptag=angular.module('apptag', ['ui.router']).config(function($sceProvider){
    $sceProvider.enabled(false);
});
//添加http拦截器
apptag.config(["$httpProvider", function ($httpProvider) {   
    $httpProvider.interceptors.push('httpInterceptor');  
}]); 

2. 自定义拦截器

//loading  
apptag.factory('httpInterceptor', ["$rootScope", function ($rootScope) {  
    //设置加载时httpProvider请求和返回的加载状态
    var httpInterceptor = {
        request: function (config) { 
            //start 开始加载
            $rootScope.loading = true;  
            return config;  
        },  
        response: function (response) { 
            //end 结束加载 
            $rootScope.loading = false;  
            return response;  
        }  
    };  
    return httpInterceptor;  
}]); 

3.自定义angularjs遮罩组件

//该遮罩template是测试demo,如果觉得不好看,可以自己在网上找些好看的,修改template即可
apptag.directive('loading', function(){  
    return {  
        restrict: 'E',  
        transclude: true,  
        template: '<div ng-show="loading" class="loading" id="allDiv"  style="position:fixed; top:0px; left:0px; width:100%; height:100%; display:none; background-color:#000; opacity: 0.5; z-index:99999;">'  
        +'<img alt="" src="img/loading.gif" style="vertical-align: middle;width:100px; height:100px; position: absolute; top:50%; left:50%; margin-top: -50px; margin-left:-50px;"/></div>',  
        link: function (scope, element, attr) {  
            scope.$watch('loading', function (val) {
                if (val){  
                    document.getElementById("allDiv").style.display = "block";  
                }else{  
                    document.getElementById("allDiv").style.display = 'none';  
                }  
            });  
        }  
    }  
});

4.见证结果的时刻

在需要加载的页面添加下面代码,位置放在body标签里

<loading></loading>

如斯:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值