Javascript 如何在angularjs中存储和检索搜索参数?
我有一个Angular应用程序,有时我想:Javascript 如何在angularjs中存储和检索搜索参数?,javascript,angularjs,angular-ui-router,browser-history,html5-history,Javascript,Angularjs,Angular Ui Router,Browser History,Html5 History,我有一个Angular应用程序,有时我想: 为当前显示的页面存储当前输入的表单变量。这可以是搜索词或其他用户输入 如果用户返回历史记录,请确保再次使用相同的搜索参数 我查看了ngRoute、stateProvider和html历史记录,但没有找到一个好方法。它看起来应该很常见,所以我想我还不知道怎么做。为了在我们当前的项目中处理这个问题,我们声明了一个指令,它监视模型并将这个值绑定到数据服务中的一个变量。此外,在呈现时,该指令检查是否已在数据服务中设置了适当的值。如果是,则将模型设置为此值
- 为当前显示的页面存储当前输入的表单变量。这可以是搜索词或其他用户输入
- 如果用户返回历史记录,请确保再次使用相同的搜索参数
我查看了ngRoute、stateProvider和html历史记录,但没有找到一个好方法。它看起来应该很常见,所以我想我还不知道怎么做。为了在我们当前的项目中处理这个问题,我们声明了一个指令,它监视模型并将这个值绑定到数据服务中的一个变量。此外,在呈现时,该指令检查是否已在数据服务中设置了适当的值。如果是,则将模型设置为此值 根据注释中的要求,my
存储服务
:
'use strict';
/**
* storage wrapper for session- or local-storage operations
*/
app.factory('StorageService', function(
$rootScope,
$http,
$location) {
/**
* get an item
*
* @param item - string - the item identifier
* @return - mixed -
*/
var get = function(item) {
return JSON.parse(sessionStorage.getItem(item) ||localStorage.getItem(item));
};
/**
* set an item
*
* @param item - string - the item identifier
* @param value - mixed - the value to set
* @param usePersistentStorage - boolean - the flag for session- or local-storage
* @return void
*/
var set = function(item, value, usePersistentStorage) {
var obj = {
value: value,
ts: new Date().getTime()
};
window[usePersistentStorage ? 'localStorage' : 'sessionStorage'][value === null ? 'removeItem' : 'setItem'](item, JSON.stringify(obj));
};
/**
* remove an item
*
* @param item - string - the item identifier
* @return void
*/
var remove = function(item) {
set(item, null, true);
set(item, null);
};
/**
* clear the whole session- and local-storage
*
* @return void
*/
var clear = function() {
sessionStorage.clear();
localStorage.clear();
};
/**
* check if item has expired
*
* @return boolean
*/
var checkExpiration = function(str, minutes) {
var now = new Date(),
nowts = now.getTime(),
item = get(str);
if(item && typeof item.ts != 'undefined' && (new Date(nowts) - new Date(item.ts) < minutes * 60 * 1000)) {
return true;
} else {
remove(str);
return false;
}
};
return {
get: get,
set: set,
remove: remove,
clear: clear,
checkExpiration: checkExpiration
};
}
“严格使用”;
/**
*用于会话或本地存储操作的存储包装器
*/
应用程序工厂('StorageService',功能(
$rootScope,
$http,
$location){
/**
*得到一件物品
*
*@param item-string-项目标识符
*@返回-混合-
*/
var get=函数(项){
返回JSON.parse(sessionStorage.getItem(item)| | localStorage.getItem(item));
};
/**
*设置项目
*
*@param item-string-项目标识符
*@param value-mixed-要设置的值
*@param usePersistentStorage-boolean-会话或本地存储的标志
*@返回无效
*/
变量集=函数(项、值、usePersistentStorage){
var obj={
价值:价值,
ts:new Date().getTime()
};
窗口[usePersistentStorage?'localStorage':'sessionStorage'][value==null?'removeItem':'setItem'](item,JSON.stringify(obj));
};
/**
*删除项目
*
*@param item-string-项目标识符
*@返回无效
*/
var remove=功能(项目){
设置(项,空,真);
set(item,null);
};
/**
*清除整个会话和本地存储
*
*@返回无效
*/
var clear=function(){
sessionStorage.clear();
localStorage.clear();
};
/**
*检查物品是否过期
*
*@返回布尔值
*/
var checkExpiration=函数(str,分钟){
var now=新日期(),
nowts=now.getTime(),
item=get(str);
if(item&&typeof item.ts!=“未定义”&(新日期(nowts)-新日期(item.ts)
)) 我过去通过在对象中保存视图状态的服务来保存视图状态 对我想要维护的字段的任何引用(如表的排序列或特定字段的值)都将保存在服务的视图状态对象中,而不是保存在控制器/范围中 当控制器通过查找特定url参数或状态(例如#/search?type=new)进行初始化时,它将检查页面传输的“源”或“类型”。如果它被认为是一个新的搜索,它将重置这些值。否则,它将显示并使用以前使用的值 应用程序重新加载将清除服务中的数据,从而提供一个全新的表单
我上面描述的方法很简单,因为angular可以为您处理节省。服务是单例的,因此通过直接绑定到服务的字段,它将自动经受路由更改 在你看来:
<input ng-model="criteria.firstName">
如果希望仅在特定点保存视图状态,可以在页面更改/路由更改事件上设置事件处理程序,并在该点复制数据
$scope.$on('$locationChangeStart', function(next, current) {
//code to copy/save fields you want to the Service.
});
根据您所描述的内容,我认为有几种方法可以做到这一点 在大多数浏览器中都有这样的功能,即使如此,也有相应的功能。这意味着您使用名称/值对进行存储 下面是一个简单的例子:
var searchParameters = {
filters: [
'recent'
],
searchString: 'bacon'
}
// Store the value(s)
localStorage.setItem('searchParameters', JSON.stringify(searchParameters));
// Retrieve the value(s)
searchParameters = JSON.parse(localStorage.getItem('searchParameters'));
// Delete the value(s)
localStorage.removeItem('searchParameters');
根据您的流程,您可以使用浏览器历史堆栈。因此,如果有人搜索
bacon
,那么您可以将他们发送到附加有?query=bacon
的页面。这将允许您轻松维护历史记录,并允许轻松使用“后退”按钮。归根结底,一切都取决于应用程序的设置方式,以及最佳选择。根据需求,还可以通过其他方式实现这一点。例如,如果需要跨设备同步,则需要实现服务器端组件来存储值并检索它们。有几种方法,其中两种方法似乎非常可靠。我最终选择了应用程序的第一种方法,因为我的搜索参数需要传播到其他控制器
把它们储存在饼干里
js提供了允许在浏览器上获取/设置参数的功能。我将其用作搜索参数的true源
例如:
search.service.js
angular
.module('app')
.service('SearchService', SearchService);
SearchService.$inject = [
'$cookies'
];
function SearchService(
$cookies
) {
var searchCookieKey = 'searchHistoryCookieKey';
var searchCookieMaxSize = 10;
return {
search: search,
getSearchHistory: getSearchHistory
};
function search(arg1, arg2) {
storeSearchHistory({arg1: arg1, arg2: arg2});
// do your search here
// also, you should cache your search so
// when you use the 'most recent' params
// then it won't create another network request
}
// Store search params in cookies
function storeSearchHistory(params) {
var history = getSearchHistory();
history.unshift(params); // first one is most recent
if(history.length > searchCookieMaxSize) {
history.pop();
}
$cookies.putObject(searchCookieKey, history);
}
// Get recent history from cookies
function getSearchHistory() {
return $cookies.getObject(searchCookieKey) || [];
}
}
.state('search', {
url: "/search",
templateUrl: "/dashboard/search/templates/index.html",
controller: 'SearchController',
resolve: {
searchResults: ['SearchService', '$stateParams', function(SearchService, $stateParams) {
if(!$stateParams.arg1 || !$stateParams.arg2) {
var history = SearchService.getSearchHistory();
var mostRecent = history.length ? history[0] : null;
if(mostRecent) {
return SearchService.search(mostRecent.arg1, mostRecent.arg2);
}
}
return SearchService.search($stateParams.arg1, $stateParams.arg2);
}]
}
})
app.states.js
angular
.module('app')
.service('SearchService', SearchService);
SearchService.$inject = [
'$cookies'
];
function SearchService(
$cookies
) {
var searchCookieKey = 'searchHistoryCookieKey';
var searchCookieMaxSize = 10;
return {
search: search,
getSearchHistory: getSearchHistory
};
function search(arg1, arg2) {
storeSearchHistory({arg1: arg1, arg2: arg2});
// do your search here
// also, you should cache your search so
// when you use the 'most recent' params
// then it won't create another network request
}
// Store search params in cookies
function storeSearchHistory(params) {
var history = getSearchHistory();
history.unshift(params); // first one is most recent
if(history.length > searchCookieMaxSize) {
history.pop();
}
$cookies.putObject(searchCookieKey, history);
}
// Get recent history from cookies
function getSearchHistory() {
return $cookies.getObject(searchCookieKey) || [];
}
}
.state('search', {
url: "/search",
templateUrl: "/dashboard/search/templates/index.html",
controller: 'SearchController',
resolve: {
searchResults: ['SearchService', '$stateParams', function(SearchService, $stateParams) {
if(!$stateParams.arg1 || !$stateParams.arg2) {
var history = SearchService.getSearchHistory();
var mostRecent = history.length ? history[0] : null;
if(mostRecent) {
return SearchService.search(mostRecent.arg1, mostRecent.arg2);
}
}
return SearchService.search($stateParams.arg1, $stateParams.arg2);
}]
}
})
如果您没有缓存这些搜索网络呼叫,那么您的应用程序将需要等待请求返回,从而降低应用程序的速度
在美国传递它们
您可以创建一个包含
$stateParams
的父控制器,子控制器将继承这些参数。返回/前进或在子状态之间访问时,不会覆盖参数。但是,当使用特定参数移动状态时,它们将被覆盖。因此,在状态之间移动时,您只需明确指定这些父级的$stateParams
。当您说搜索参数时,您指的是搜索参数吗