angular ui router——在用户返回到上一个视图时保留数据



我实现了一个应用程序,其中我显示结果列表,然后我允许用户选择要比较的行并显示有关它们的一些额外数据。

我使用angular ui route,我有2个视图和2个控制器,每个一个,所以我要找的是最好的方法来保持信息在第一个视图(我有所有的结果之前去比较视图),当用户回到第一个视图。

到目前为止,我所尝试的是使用$localstorage,但在第一个视图中,我有一个用户可以过滤搜索条件的表单,我也有一些<select></select>是由ajax调用加载的,所以…对于$localstorage,我保留了信息,但没有为select input设置表单细节,因为ajax调用没有执行,而且我不想总是保持本地存储,只有在用户返回预览的情况下。

下面可以看到angular route ui:

的设置
  .state('deposit', {
    url: '/deposit',
    templateUrl: './app/components/deposit/index.html',
    views: { "" : { templateUrl: './app/components/deposit/index.html' },
      "search@deposit": { templateUrl: "./app/components/deposit/search.html",
                            controller: "DepositSearchController"}
    }
  })
  .state('depositcomparison', {
    url: "/deposit/comparison",
    params: {
      ids: null,
      depositSearchData: null
    },
    templateUrl: './app/components/depositComparison/depositComparisonView.html',
    controller: 'DepositComparisonController'
  })

只有当我从比较视图返回到结果视图时,保持数据的正确方法是什么?

有比localstorage更好的方法吗?

谢谢。

/***********更新***********//*********** ajax的问题 ***********/

获取select的数据:

//...
$http.get(window.serviceUrl + '/api/institute').
  success(function(data){
    $scope.institutes = data.content;
    $scope.institutes.push({id: '0', name: 'All'});
    $localstorage.setObject('instituteData', $scope.institutes);
  }).
  error(function(data){
    console.log('Error');
  });
 //..

Check localstorage:

//..
angular.element(document).ready(function () {
    if ($localstorage.getObject('instituteData').length !== 0) {
         $scope.institutes = $localstorage.getObject('instituteData');
      }
    //else call the ajax
//..
});
Html:

<label for="forinstitute">Account Type</label>
<select id="instituteValue" class="form-control" ng-model="institute.id">
<option value=""> Select account</option>
<option ng-repeat="institute in institutes | orderBy:'name'" value="{{institute .id}}">{{institute .name}}</option>
</select>

/********************************************************/

可能是$watch的解决方案??

你可以在Angular服务的视图中存储任何你想要显示的数据。然后将该服务注入到控制器中。数据会保存在服务中,因为Angular中的服务都是单例的。

查看ui router extras http://christopherthielen.github.io/ui-router-extras/#/sticky尝试使用粘性状态,但要注意,当你返回到该视图时,该视图上的控制器不会被重新初始化。

使用例子,

$stateProvider
        //home state
         .state('home', {
            url: '/home',
            templateUrl: 'views/layout/home.html'
        })   
        //Client States
        .state('home.clients', {
            url: '/clients',
            views: {
                'clientTab@home':{
                 templateUrl: 'views/client/clients.html'
                 }
            },
             deepStateRedirect: true,
             sticky: true
           });
 $urlRouterProvider.otherwise('/');

相关内容

最新更新