在 AngularJS 中保存视图状态 [英] Save state of views in AngularJS

查看:27
本文介绍了在 AngularJS 中保存视图状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个 HTML 5 应用程序,并有一个加载用户评论的视图.它是递归的:任何评论都可以有可点击的子评论,这些子评论在同一个视图中加载并使用同一个控制器.

I develop a HTML 5 app, and have a view where user comments are loaded. It is recursive: any comment can have clickable sub-comments which are loading in the same view and use the same controller.

一切正常.但是,当我想回去时,评论又加载了,我失去了我加载的位置和子评论.

Everything is OK. But, when I want to go back, comments are loading again, and I lose my position and sub-comments I loaded.

返回时可以保存视图的状态吗?我想我可以使用某种技巧,例如:每次单击子评论时附加一个新视图并隐藏以前的视图.但我不知道该怎么做.

Can I save the state of the view when I go back? I thought I can maybe use some kind of trick, like: append a new view any time I click on sub-comment and hide the 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 */);
});

您应该将初始化代码更改为您的服务,以及那里的状态,这样您就可以在多个视图之间保持状态:

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!
    }
  };
});

当您来回切换视图时,它们的状态将被保留,因为您的服务是单例,在您第一次将其注入控制器时已初始化.

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,但它目前处于实验阶段(并将在 angular 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆