ionic專案中跨頁面傳遞引數的幾種方式
阿新 • • 發佈:2019-01-25
1、使用angularjs自帶的$cacheFactory服務
$cacheFactory 從字面直譯即為快取工廠,可以用它來生成快取物件,快取物件以key-value的方式進行資料的儲存,在整個應用內是單例的,可以在service或者controller中注入這個服務,然後就可以用它來自由的存取物件以及各種變數,下面是一個簡單例子
.controller('AppCtrl', function ($scope, $ionicModal, $timeout, $cacheFactory) { var user = {name: 'jax', age: 18, sex: '男'}; var user_cache = $cacheFactory("user_cache"); //宣告一個user_cache快取物件 user_cache.put("lol",user); //放入快取物件
.controller('PlaylistCtrl', function ($scope, $stateParams, $cacheFactory) { var user_cache = $cacheFactory.get("user_cache"); //取出名為user_cache的快取物件 var user = user_cache.get("lol"); //取出快取物件中鍵值為lol的物件 // user_cache.remove("lol"); //刪除鍵值為lol對應的值 // user_cache.removeAll(); //清除快取物件中所有的鍵值對 // user_cache.destroy(); //銷燬user_cache快取物件 console.log(user); });
當從AppCtrl對應頁面切換到PlaylistCtrl對應的頁面時,瀏覽器控制檯列印結果:
$cacheFactory常用的幾個方位api如下:
- {{*}}
get({string} key)
— 返回與key
對應的value
值,如果未命中則返回undefined
。
- {void}
remove({string} key)
— 從快取中刪除一個鍵值對
- {void}
removeAll()
— 刪除所有快取中的資料
- {void}
destroy()
— 刪除從$cacheFactory
引用的這個快取.
<ion-item href="#/app/playlists/{{playlist.id}}"> //playlists.html頁面
.controller('PlaylistCtrl', function ($scope, $stateParams, $cacheFactory) {
var user_cache = $cacheFactory.get("user_cache"); //取出名為user_cache的快取物件
var user = user_cache.get("lol"); //取出快取物件中鍵值為lol的物件
// user_cache.remove("lol"); //刪除鍵值為lol對應的值
// user_cache.removeAll(); //清除快取物件中所有的鍵值對
// user_cache.destroy(); //銷燬user_cache快取物件
console.log(user);
var playlistId=$stateParams.playlistId; //用$stateParams 取值
console.log("playlistId:"+playlistId);
});
需要注意的是必須在app.js路由中配置接受這個引數
.state('app.single', {
url: '/playlists/:playlistId', //配置多個引數用:a/:b/:c
views: {
'menuContent': {
templateUrl: 'templates/playlist.html',
controller: 'PlaylistCtrl'
}
}
3、service或者factory傳值(service跟factory中都是單例模式,定義的變數在整個應用內唯一)
定義變數data
angular.module('starter.controllers', [])
.service('dataService',function () {
var data="I come from service"; //定義變數
return{
getData:function () {
return data;
}
}
})
在controller中取出變數
.controller('PlaylistCtrl', function ($scope, $stateParams, $cacheFactory,dataService) {
console.log("sercice data:"+dataService.getData()); //得到data
});
4、使用H5本地儲存localStorage或者sessionStorage(還有indexDB,websql在資料量較大情況下使用)
getItem //取記錄
setItem//設定記錄
removeItem//移除記錄
key//取key所對應的值
clear//清除記錄
鍵值對儲存,用法也是非常簡單,上面給出了常用的api,