Angularjs:如何在返回时恢复到上一个​​视图中运行时加载的 DOM 元素(保留状态) [英] Angularjs: how to revert back to the runtime loaded DOM elements in the previous view on going back (preserve state)

查看:16
本文介绍了Angularjs:如何在返回时恢复到上一个​​视图中运行时加载的 DOM 元素(保留状态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有两个视图的角度应用程序:

I have an angular application which has two views:

1) 列表视图

2) 详细视图

当您点击列表视图中的缩略图时,您将进入详细信息视图,路线如下:

when you click on the thumbnail from list view you go to detail view, here is the route:

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/list', {
        templateUrl: 'partials/list.html',
        controller: 'ListCtrl',

      }).
      when('/list/:id', {
        templateUrl: 'partials/detail.html',
        controller: 'DetailCtrl',

      }).
      otherwise({
        redirectTo: '/list'
      });
  }]);

现在'listCtrl'控制器中有一个函数loadmore用于加载

Now there is a function loadmore in 'listCtrl' controller which is used to load

myControllers.controller('ListCtrl', ['$scope', '$location', 'Troll', '$http',

function ($scope, $location, Troll, $http) {
    $scope.Trolls = Troll.query();
    $scope.orderProp = 'popular';
    $scope.fromData = {};
    //console.log($scope.Trolls);
    //this will be used to fetch the data in json which is defined in services.js

    $scope.loadmore = function () {
        jQuery.ajax({
            url: 'trolls/trolls.php?troll_index=' + $('#main-content #item-list .sub-item').size(),
            type: 'GET',
            async: false,
            data: {},
            dataType: 'json',
            success: function (response) {


                if (response != null) {
                    $.each(response, function (index, item) {

                        $scope.Trolls.push({
                            UID: response[index].UID,
                            id: response[index].id,
                            popular: response[index].popular,
                            imageUrl: response[index].imageUrl,
                            name: response[index].name,
                            tags: response[index].tags,
                            category: response[index].category
                        });

                    });
                }
            },
            complete: function () {},
            error: function () {
                console.log('Failed!');
            }
        });
        $scope.text = 'Hello, Angular fanatic.';
        $http.get('trolls/trolls.php?troll_id=' + Troll);

    }

}]);

问题:现在的问题是,单击加载更多后,如果我转到详细信息视图并返回列表视图,我新加载的 div 不见了,我该如何保留它们?

PROBLEM: now the problem is, After clicking on loadmore if i go to detail view and i come back on list view my newly loaded divs are gone how do i preserve them??

推荐答案

当你改变路由时,负责该路由的控制器在路由加载时初始化,当路由改变时销毁.所以你丢失数据的原因是控制器重新初始化并且以前的数据不存在.

When you change routes the controller that is in charge of that route is initialized when the route is loaded and destroyed when the route is changed. So the reason you lose your data is the controller is reinitialized and the previous data never exists.

有两种方法可以解决这个问题.

There are two ways to fix this.

  1. 未被破坏的高级控制器 - 可能存在于身体上 - 这会将其范围传递给子控制器.但这并不是真正的关注点模块化.对于这个问题...对于其他问题非常有用 - 身份验证、配置文件等.

  1. Higher level controller that is not destroyed - could potentially live on the body - this passes its scope to the children controllers. But this is not a true modularization of concerns. For this issue... Can be very useful for other issues - Authentication, Profile, etc.

我提倡的方法是将其拉入服务中,例如 - listService - 这将获取并缓存数据,并在重新加载时将其传递回 listController,从而防止数据丢失.

The way I would advocate is to pull this into a service for example - listService - this will fetch and cache the data and pass it back to the listController when its reloaded, thus preventing the data from being lost.

<小时>

第一种解决方法可能是这样...

因此,如果您有一个更高级别的控制器负责获取数据或将其移动到我会做的服务中,那么从 loadMore 函数加载的数据将继续存在,但它需要在路由更改时不会破坏的更高父作用域上.

So if you have a higher level controller in charge of fetching the data or move it into a service which is what I would do, then the data that is loaded from loadMore function will continue to be there, but it needs to be on a higher parent scope that is not destroyed on the route change.

HTML:

<body ng-controller="ApplicationController">
     <!-- Code Here -->
</body>

控制器:

myControllers.controller('ApplicationController', function($scope) {
     var data = [];

     $scope.loadmore = function () {
        // Use Angular here!!! $http not jQuery! 
        // Its possible to write a complete Angular app and not ever true jQuery
        // jQuery Lite the Angular implementation will be used though
        jQuery.ajax({
            url: 'trolls/trolls.php?troll_index=' + $('#main-content #item-list .sub-item').size(),
            type: 'GET',
            async: false,
            data: {},
            dataType: 'json',
            success: function (response) {


                if (response != null) {
                    $.each(response, function (index, item) {

                        data.push({
                            UID: response[index].UID,
                            id: response[index].id,
                            popular: response[index].popular,
                            imageUrl: response[index].imageUrl,
                            name: response[index].name,
                            tags: response[index].tags,
                            category: response[index].category
                        });

                    });
                }

                return data;

            }
            error: function () {
                console.log('Failed!');
            }
        });

    }
});

但是我真的不喜欢这种方法,因为它有点hacky...并且使用了jQuery...

However I dont really like this approach as its a bit hacky...and jQuery is used...

第二种使用服务来获取/缓存的方法:

所以让我们将其拉入服务中.

So lets pull it into a service instead.

myServices.factory('listService', function($http, $q) {

   var//iable declaration 
      service = {},
      list = []
   ;
   /////////////////////   
   //Private functions//
   /////////////////////

   function loadMore(url) {
      var deferred = $q.defer();

      $http({ method: 'GET', url: url }) // Need to pass in the specific URL maybe from the DOM scoped function?
      .success(function(data) {
         deferred.resolve(data);
      })
      .error(function() {
        deferred.reject();
        //Do error things
      });   

     return deferred.promise; 
   }

   ////////////////////
   //Public Functions//
   ////////////////////

   service.loadMore = function(url) { 
      // Used for loading more data
      loadMore(url).then(function(data) {
        list.push(data);
        return list
      });
   }

   service.getList = function() {
      // Returns the currently loaded data
      return list;
   }

 return service;

});

然后在您的控制器中:

myControllers.controller('ListCtrl', ['$scope', '$location', 'Troll', listService

function ($scope, $location, Troll, listService) {
    $scope.Trolls = Troll.query();
    $scope.orderProp = 'popular';
    $scope.fromData = {};


    $scope.loadmore = function(subItemSize) { //add url specific params here
       var url = 'trolls/trolls.php?troll_index=' + subItemSize;
       return listService.loadMore(url);
    };

}]);

这篇关于Angularjs:如何在返回时恢复到上一个​​视图中运行时加载的 DOM 元素(保留状态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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