ionic 開發當中,有一些常用的方法。

在開發項目的時候,有些常用的功能封裝到一個類裏。


以後要用的話,直接導入過來就可以用了,有一些方法是從網站複製過來的,有些方法是網上覆制過來,然後自己修改了一下,標記一下吧!


    /**
     * 一些共用方法
     * @class Utility
     */
 angular.module('LHB')
 .service('Utility', ['$rootScope', '$timeout', '$interval', "XiaotuniVersion", function ($rootScope, $timeout, $interval, XiaotuniVersion) {  //應用範圍:service,controller,run,factory

        var _TempSaveContent = {};
        var __key = "Xiaotuni@pz!365_com";

        /**
         * 設置內容,這裏主要是用來存放臨時數據的。
         * @method _SetContent
         * @param key  鍵值,用於下次的時候獲取內容用的。其實就是 _TempSaveContent的屬性名稱。
         * @param content 要存儲的內容
         * @param isSaveLocalStorage 是否保存到本地存儲裏面
         * @param IsUser 根據用戶uid 來獲取緩存裏的數據。
         * @private
         */
        var _SetContent = function (key, content, isSaveLocalStorage, IsUser) {
            try {
                if (isSaveLocalStorage) {
                    var __Content = content;
                    if (IsUser) {
                        var __CheckIn = _TempSaveContent[_Const.API_CheckIn];
                        if (null !== __CheckIn && typeof  __CheckIn !== "undefined") {
                            __Content = {};
                            __Content[__CheckIn.uid] = content;
                        }
                    }
                    __Content = JSON.stringify(__Content);
                    //__content = CryptoJS.AES.encrypt(__Content, __key);
                    window.localStorage.setItem(key, __Content);
                }
                _TempSaveContent[key] = content;
            }
            catch (ex) {
                console.log(ex);
            }
        }

        /**
         * 刪除指定字段值。
         * @method __RemoveContent
         * @param key
         * @return {null}
         * @private
         */
        var __RemoveContent = function (key, IsRemoveLocalStorage) {
            try {
                if (null === key || typeof key === 'undefined') {
                    return;
                }
                if (_TempSaveContent.hasOwnProperty(key)) {
                    delete _TempSaveContent[key];
                    //_TempSaveContent[key] = null;
                }
                if (IsRemoveLocalStorage) {
                    window.localStorage.removeItem(key);
                }
            }
            catch (ex) {
                __PrintLog(ex.toString());
            }
        }

        /**
         * 獲取內容,
         * @method _GetContent
         * @param key 健名稱。其實就是 _TempSaveContent的屬性名稱。
         * @return {*} 返回內容
         * @private
         */
        var _GetContent = function (key, IsUser) {
            try {
                var __Content = null;
                if (_TempSaveContent.hasOwnProperty(key)) {
                    __Content = _TempSaveContent[key];
                    return __Content;
                }
                if (null === __Content || typeof __Content === "undefined") {
                    var _value = window.localStorage.getItem(key);
                    if (null != _value && '' !== _value && typeof _value !== 'undefined') {
                        /*  // Decrypt  解密
                         var bytes = CryptoJS.AES.decrypt(_value, __key);
                         _value = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
                         _TempSaveContent[key] = _value;
                         */
                        var __JSONValue = JSON.parse(_value);
                        _TempSaveContent[key] = JSON.parse(_value);
                        if (IsUser) {
                            if (_TempSaveContent.hasOwnProperty(_Const.API_CheckIn)) {
                                var __CheckInfo = _TempSaveContent[_Const.API_CheckIn];
                                if (__JSONValue.hasOwnProperty(__CheckInfo.uid)) {
                                    _TempSaveContent[key] = __JSONValue[__CheckInfo.uid];
                                }
                                else {
                                    _TempSaveContent[key] = null;
                                }
                            }
                            else {
                                _TempSaveContent[key] = null;
                            }
                        }
                        __Content = _TempSaveContent[key];
                    }
                }

                return __Content;
            }
            catch (ex) {
                console.log(ex);
                return null;
            }
        }

        /**
         * 清空本地存儲
         * @method __ClearLocalStorage
         * @private
         */
        var __ClearLocalStorage = function () {
            try {
                __RemoveContent(_Const.AddressInfo, true);
                __RemoveContent(_Const.CacheUserCartGoods, true);
                __RemoveContent(_Const.CacheUserDefaultAddress, true);
                __RemoveContent(_Const.CacheUserHistorySearch, true);
                __RemoveContent(_Const.CacheUserLatelySelectAddress, true);
                __RemoveContent(_Const.AddressManagerSelectAddress, true);
            }
            catch (ex) {
                __PrintLog(ex.toString());
            }
        };

        /**
         * 清空當前頁面緩存數據
         * @method __ClearCacheData
         * @private
         */
        var __ClearCacheData = function () {
            _TempSaveContent = {};
        };

        /**
         * 獲取對像屬性值
         * @method __GetObjectPropertyValue
         * @param obj 對象
         * @param key 屬性
         * @param IsReturnNull 默認(null)是返回 null,否則返回 ''
         * @return {*}
         * @private
         */
        var __GetObjectPropertyValue = function (obj, key, IsReturnNull) {
            if (null === obj || typeof obj === 'undefined' || '' === obj
                || null == key || typeof key === 'undefined' || '' === key) {
                return IsReturnNull === false ? '' : null;
            }
            if (obj.hasOwnProperty(key)) {
                var __value = obj[key];
                return obj[key]
            }
            return IsReturnNull === false ? '' : null;
        }

        /**
         * 觸發事件
         * @method __Emit
         * @param eventName 事件名稱
         * @param {object} param1 參數1
         * @param {object} param2 參數2
         * @param {object} param3 參數3
         * @param {object} param4 參數4
         * @param {object} param5 參數5
         * @param {object} param6 參數6
         * @param {object} param7 參數7
         * @private
         */
        var __Emit = function (eventName, param1, param2, param3, param4, param5, param6, param7) {
            $rootScope.$emit(eventName, param1, param2, param3, param4, param5, param6, param7);
        }

        /**
         * 廣播事件
         * @method __Broadcast
         * @param eventName 廣播事件名稱
         * @param {object} param1 參數1
         * @param {object} param2 參數2
         * @param {object} param3 參數3
         * @param {object} param4 參數4
         * @param {object} param5 參數5
         * @param {object} param6 參數6
         * @param {object} param7 參數7
         * @private
         */
        var __Broadcast = function (eventName, param1, param2, param3, param4, param5, param6, param7) {
            $rootScope.$broadcast(eventName, param1, param2, param3, param4, param5, param6, param7);
        }

        /**
         * 彈出對話框
         * @method __Alert
         * @param {object} param 參數
         * @example
         *  Utility.Alert({title: '購物袋', template: '請選擇要結算的商品'});
         * @constructor
         */
        var __Alert = function (param) {
            $rootScope.$emit(_Const.Alert, param);
        };

        /**
         * 打印輸出日誌
         * @method __PrintLog
         * @param {object} args 內容
         * @private
         */
        var __PrintLog = function (args) {
            try {
                var __callmethod = '';
                try {
                    throw new Error();
                } catch (e) {
                    //console.log(e.stack);
                    __callmethod = e.stack.replace(/Error\n/).split(/\n/)[1].replace(/^\s+|\s+$/, "");
                }

                var _curDate = new Date();
                var _aa = _curDate.toLocaleDateString() + " " + _curDate.toLocaleTimeString() + "." + _curDate.getMilliseconds();
                console.log("--begin->", _aa, ' call method :', __callmethod);
                var __content = "";
                if (angular.isObject(args) || angular.isArray(args)) {
                    __content = JSON.stringify(args);
                }
                else {
                    __content = args;
                }
                console.log(__content)
            }
            catch (ex) {
                console.log('---------輸出日誌,傳入的內容傳爲JSON出現在異常--------------');
                console.log(ex);
                console.log('---------輸出日誌,內容爲下--------------');
                console.log(args);
            }
        };

        /**
         * 判斷輸入的是否是手機號
         * @method __PhonePattern
         * @param {number} phone 手機號
         * @return {boolean} true 成功;false 失敗
         * @example
         *  Utility.PhonePattern('13000100100');
         * @private
         */
        var __PhonePattern = function (phone) {
            var ex = /^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/;
            return ex.test(phone);
        }

        /**
         * 密碼驗證
         * @method __PasswordPattern
         * @param {string} password 密碼
         * @return {boolean} true 成功;false 失敗
         * @private
         */
        var __PasswordPattern = function (password) {
            //test("/^[_0-9a-z]{6,16}$/i");
            var ex = /^[_0-9a-zA-Z]{6,25}$/;
            return ex.test(password);
        }

        /**
         * 是否含有中文(也包含日文和韓文)
         * @method __IsChineseChar
         * @param {string} str 要判斷的內容
         * @return {boolean} true:成功;false:失敗.
         * @private
         */
        var __IsChineseChar = function (str) {
            //var reg = !/^[\u4E00-\u9FA5]/g;    //\uF900-\uFA2D
            //return !/^[\u4e00-\u9fa5]+$/gi.test(str);//.test(str);

            var regu = "^[\u4e00-\u9fa5]+$";
            var re = new RegExp(regu);
            return re.test(str);
        }

        /**
         * 同理,是否含有全角符號的函數
         * @method __IsFullWidthChar
         * @param {string} str 要判斷的內容
         * @return {boolean}  true:成功;false:失敗.
         * @private
         */
        var __IsFullWidthChar = function (str) {
            var reg = /[\uFF00-\uFFEF]/;
            return reg.test(str);
        }


        /**
         * 常量
         * @class _Const
         * @type {{}}
         * @private
         */
        var _Const = {
            FromPageUrl: "XiaotuniFromPageName",//
            IsFirstStartApp: 'XiaotuniIsFirstStartApp', //是否是第一次啓動APP
            LoadingHide: 'XiaotuniLoadingHide',      //隱藏加載
            Loading: 'XiaotuniLoading',    //顯示加載
            LoadingDefined: "XiaotuniLoadingDefined",
            Alert: 'XiaotuniAlert',        //彈出對話框
            HomePage: 'tab.home.goods',        //跳到首頁
            GoBack: 'XiaotuniGoBack',      //返回
            GoToPage: 'XiaotuniGoToPage',  //頁面跳轉
            GoHome: 'XiaotuniGoHome',      //轉到tab的首頁上去,
            ToPage: "XiaotuniToPage",      //這個是
            FromWhereEnterSearch: "XiaotuniFromWhereEnterSearch",//從哪個界面裏進入搜索界面的。

            CacheUserCartGoods: "XiaotuniCacheUserCartGoods", //用於臨時保存當前購物袋裏goodsId,amount。這主要用於首頁,商品搜索頁時顯示數量用的。
            CacheUserHistorySearch: "XiaotuniCacheUserHistorySearch",//保存當前歷史搜索記錄
            CacheUserDefaultAddress: "XiaotuniCacheUserDefaultAddress",//用戶默認地址
            CacheUserLatelySelectAddress: "XiaotuniCacheUserLatelySelectAddress",    //保存用戶最近選中的地址。
            CartListShippingModel: 'XiaotuniCartListShippingModel',   //購物袋配送方式
            GifiCertificate: 'XiaotuniGifiCertificate',                //優惠券
            GoodsListSelect: 'XiaotuniGoodsListSelectIndex',          //當前選中商品標籤搜索
            AddressInfo: 'XiaotuniAddressInfo',                         //地址信息
            AddressManagerSelectAddress: 'XiaotuniAddressManagerSelectAddress',//訂單界面,當前選中的地址
            AddressManagerAddressList: 'XiaotuniAddressManagerAddressList',    //地址管理,所有地址信息
            PositionInfo: 'XiaotuniSavePositionInfo',                         //位置信息
            OrderDetail: 'XiaotuniOrderDetail',              //訂單詳情
            OrderStatusParam: "XiaotuniOrderStatusParam",//訂單狀態參數
            API_Locate: 'XiaotuniApiLocateResult',                            //本地位置定位
            API_CheckIn: 'XiaotuniApiCheckinResult',                          //登錄
            API_Coupon: 'XiaotuniApiCoupon',                                   //優惠券
            API_Build: 'XiaotuniApiBuild',                                     //生成訂單
            API_Order_Detail: 'XiaotuniApiOrderDetail',                       //訂單明細
            API_Order_Total: 'XiaotuniApiOrderTotal',                         //訂單統計
            API_Order_Status: 'XiaotuniApiOrderStatus',                       //訂單統計
            API_TrolleySettle: 'XiaotuniApiTrolleySettle',                     //購物袋結算
            API_TrollerDelete: 'XiaotuniApiTrollerDelete',                    //刪除購物袋
            API_TrollerDeleteError: 'XiaotuniApiTrollerDeleteError',         //刪除購物袋
            API_TrollerDeleteComplete: 'XiaotuniApiTrollerDeleteComplete',  //刪除購物袋
            API_Goods_Detail: 'XiaotuniApiGoodsDetail',                       //商品明細
            API_Address_Delete: 'XiaotuniApiAddressDelete',
            API_Version: "XiaotuniApiVersion",//版本信息

            GetLocation: 'onXiaotuniGetLocation',                             //獲取定位
            GetLocationComplete: 'onXiaotuniGetLocationComplete',           //定位完成
            GetLocationCompleteNotFound: "onXiaotuniGetLocationCompleteNotFound", //沒有定位到商鋪
            GetLocationError: 'onXiaotuniGetLocationError',                  //定位出錯
            OnBarcodeScanner: 'onXiaotuniBarcodeScanner',                   //條碼掃描
            OnActionSheet: "onXiaotuniActionSheet",     //彈出內容出來。
            OnGetUpdateTabsIconStatus: "onXiaotuniGetUpdateTabsIconStatus",//更新狀態圖標
            OnGetUpdateTabsIconStatusComplete: "onXiaotuniUpdateTabsIconStatusComplete",//更新狀態圖標
            OnImageLoadingComplete: "onXiaotuniImageLoadingComplete",//圖片加截完成。
            OnUpdateSettle: "onXiaotuniUpdateSettle",
            OnEnterSearch: "onXiaotuniEnterSearch",//點擊搜索的時候事件。
            OnOrderConfirm: "onXiaotuniOrderConfirm",//訂單確認
            OnOrderCancel: "onXiaotuniOrderCancel",//訂單取消
            OnGoodsDetailImage: "onXiaotuniGoodsDetailImage",//商品明細詳情裏的圖片。
            OnOrderTotal: "onXiaotuniOrderTotal",//訂單統計總數
            OnTralley: "onXiaotuniTralley",//
            OnVersion: "onXiaotuniVersion",//版本信息
            OnCloseInAppBrowser: "onXiaotuniCloseInAppBrowser",//關閉瀏覽器窗體
        }

      
        /**
         * 對Date的擴展,將 Date 轉化爲指定格式的String
         * 月(M)、日(d)、小時(h)、分(m)、秒(s)、季度(q) 可以用 1-2 個佔位符,
         * 年(y)可以用 1-4 個佔位符,毫秒(S)只能用 1 個佔位符(是 1-3 位的數字)
         * @method __FormatDate
         * @param fmt
         * @param date
         * @return {*}
         * @example
         *  Utility.FormatDate("yyyy-MM-dd hh:mm:ss.S",new Date());
         * @constructor
         */
        var __FormatDate = function (fmt, date) {
            var __this = new Date();
            if (null !== date) {
                if (angular.isDate(date)) {
                    __this = date;
                }
                else {
                    try {
                        __this = new Date(date);
                    }
                    catch (ex) {
                        __this = new Date();
                    }
                }
            }
            var o = {
                "M+": __this.getMonth() + 1, //月份
                "d+": __this.getDate(), //日
                "H+": __this.getHours(), //小時
                "m+": __this.getMinutes(), //分
                "s+": __this.getSeconds(), //秒
                "q+": Math.floor((__this.getMonth() + 3) / 3), //季度
                "S": __this.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) {
                var a = /(y+)/.test(fmt);
                var fmt1 = fmt.replace(RegExp.$1, (__this.getFullYear() + "").substr(4 - RegExp.$1.length));
                fmt = fmt1;
            }

            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return fmt;
        }

        /**
         * 判斷是第一次啓動。位置是否已經定位了。
         * @method __JudgeIsFirstStartAndLocate
         * @private
         */
        var __JudgeIsFirstStartAndLocate = function () {
            var _IsFirstStartApp = _GetContent(_Const.IsFirstStartApp);
            if (null === _IsFirstStartApp) {
                __Emit(_Const.ToPage, "startapp");
                return;
            }
            var __location = _GetContent(_Const.API_Locate);
            if (null === __location) {
                __Emit(_Const.ToPage, "location");
                return;
            }
            return false;
        }

        /**
         * 解析URL地址
         * @method __ParseURL
         *@param {string} url 完整的URL地址
         *@return {object} 自定義的對象
         *@example
         *  用法示例:var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
         * myURL.file='index.html'
         * myURL.hash= 'top'
         * myURL.host= 'abc.com'
         * myURL.query= '?id=255&m=hello'
         * myURL.params= Object = { id: 255, m: hello }
         * myURL.path= '/dir/index.html'
         * myURL.segments= Array = ['dir', 'index.html']
         * myURL.port= '8080'
         * yURL.protocol= 'http'
         * myURL.source= 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'
         */
        var __ParseURL = function (url) {
            var a = document.createElement('a');
            a.href = url;
            return {
                source: url,
                protocol: a.protocol.replace(':', ''),
                host: a.hostname,
                port: a.port,
                query: a.search,
                params: (function () {
                    var ret = {},
                        seg = a.search.replace(/^\?/, '').split('&'),
                        len = seg.length, i = 0, s;
                    for (; i < len; i++) {
                        if (!seg[i]) {
                            continue;
                        }
                        s = seg[i].split('=');
                        ret[s[0]] = s[1];
                    }
                    return ret;
                })(),
                file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
                hash: a.hash.replace('#', ''),
                path: a.pathname.replace(/^([^\/])/, '/$1'),
                relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
                segments: a.pathname.replace(/^\//, '').split('/')
            };
        }

        var _Browser = {
            versions: function () {
                var u = navigator.userAgent, app = navigator.appVersion;
                return {
                    trident: u.indexOf('Trident') > -1, //IE內核
                    presto: u.indexOf('Presto') > -1, //opera內核
                    webKit: u.indexOf('AppleWebKit') > -1, //蘋果、谷歌內核
                    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐內核
                    mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否爲移動終端
                    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios終端
                    android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android終端
                    iPhone: u.indexOf('iPhone') > -1, //是否爲iPhone或者QQHD瀏覽器
                    iPad: u.indexOf('iPad') > -1, //是否iPad
                    webApp: u.indexOf('Safari') == -1, //是否web應該程序,沒有頭部與底部
                    weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增)
                    qq: u.match(/\sQQ/i) == " qq" //是否QQ
                };
            }(),
            language: (navigator.browserLanguage || navigator.language).toLowerCase()
        }


        var _UtilityService = {
            IsChineseChar: __IsChineseChar,//是否包含漢字
            IsFullWidthChar: __IsFullWidthChar,//是否包含全角符
            Emit: __Emit,            //事件
            Broadcast: __Broadcast,  //廣播事件
            Alert: __Alert,          //彈出對話框
            PrintLog: __PrintLog,    //打印輸入日誌
            ConstItem: _Const,      //常量
            GetContent: _GetContent, //獲取內容
            SetContent: _SetContent, //保存內容
            RemoveContent: __RemoveContent,//刪除不要的內容
            TokenApi: _TokenApi,    //訪問這些接口的時候要加token。
            ClearCacheData: __ClearCacheData,            //清空緩存數據
            ClearLocalStorage: __ClearLocalStorage,      //清空本地存儲數據
            GetObjectPropertyValue: __GetObjectPropertyValue, //獲取對象值
            PhonePattern: __PhonePattern,      //判斷是否是手機號。
            PasswordPattern: __PasswordPattern,  //密碼驗證
            FormatDate: __FormatDate,   //格式化日期
            JudgeIsFirstStartAndLocate: __JudgeIsFirstStartAndLocate,//判斷是第一啓動和位置定位
            ParseURL: __ParseURL,
            XiaotuniVersion: __XiaotuniVersion,
        };

        return _UtilityService;
    }])



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章