保存的意见AngularJS状态 [英] Save state of views in AngularJS
问题描述
我开发HTML5应用程序。
而且我有用户的评论加载一个视图。而且它是递归的 - 任何评论具有加载在同一个视图,并在同一个控制器subcomments
I developing an html5 app. And I have a view there user's comments is loading. And it's recursive - any comment has subcomments which loading in the same view and with the same controller.
一切正常。但是,当我想回去,再评论加载,而我失去了我的位置,并应重新滚动。
Everything is ok. But, when I want to go back, comments loading again, and I lose my position and should to scroll again.
所以,我的问题是。我可以保存视图的状态,当我回去。我想用那种把戏就像任何时候我点击subcomment和隐藏previous视图追加新的看法。但我不知道该怎么办了。
So, my question is. Can I save the state of the view when I go back. I thought use kind of trick like append new view any time I click on subcomment and hide previous view. But I don't know how to do it.
请,帮助。
推荐答案
是的,而不是装载并保持你的控制器内部UI的状态,你应该保持在一个服务的状态。这意味着,如果你正在做这样的:
Yes, instead of loading and keeping state of your UI inside your controllers, you should keep the state in a service. That means, if you are doing this:
app.config(function($routeProvider){
$routeProvider.when('/', {
controller: 'MainCtrl'
}).when('/another', {
controller: 'SideCtrl'
});
});
app.controller('MainCtrl', function($scope){
$scope.formData = {};
$scope./* other scope stuff that deal with with your current page*/
$http.get(/* init some data */);
});
你应该改变你的初始化code为您服务,并有国家为好,这样你可以保持多个视图之间的状态:
you should change your initialization code to your service, and the state there as well, this way you can keep state between multiple views:
app.factory('State', function(){
$http.get(/* init once per app */);
return {
formData:{},
};
});
app.config(function($routeProvider){
$routeProvider.when('/', {
controller: 'MainCtrl'
}).when('/another', {
controller: 'SideCtrl'
});
});
app.controller('MainCtrl', function($scope, State){
$scope.formData = State.formData;
$scope./* other scope stuff that deal with with your current page*/
});
app.controller('SideCtrl', function($scope, State){
$scope.formData = State.formData; // same state from MainCtrl
});
app.directive('myDirective', function(State){
return {
controller: function(){
State.formData; // same state!
}
};
});
当你去来回您的看法,他们的状态将是preserved,因为你的服务是一个单身,当你第一次注射就在你的控制器被初始化。
when you go back and forth your views, their state will be preserved, because your service is a singleton, that was initialized when you first injected it in your controller.
还有新的 ui.router
,有一个状态机,它是一个低级别版本 $ routeProvider
你可以细晶粒坚持使用状态 $ stateProvider
,但它目前的实验(和将推出的角1.3)
There's also the new ui.router
, that has a state machine, it's a low level version of $routeProvider
and you can fine grain persist state using $stateProvider
, but it's currently experimental (and will ship on angular 1.3)
这篇关于保存的意见AngularJS状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!