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

问题描述

我有一个角度应用程序,它有两种观点:

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

    }

}]);

问题
现在的问题是,
点击loadmore后,如果我去详细信息视图,我回来在列表中查看我的新加载的div都走了我如何preserve他们??

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??

推荐答案

当您更改路由时的路线被加载,在道路改变摧毁负责这条路线的控制器初始化。所以,你失去了你的数据的原因是被重新初始化控制器,绝不存在previous数据。

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当它重新加载,从被这样preventing数据丢失。

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

    }
});

不过,我真的不喜欢这种方法,因为它有点哈克......和jQuery用于...

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

使用服务来获取/缓存第二条本办法:

Second approach using a service to fetch/cache:

所以让我们把它变成一个服务,而不是。

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;

});

然后在你的控制器:

Then in your controller:

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:如何恢复到在previous针对运行时加载的DOM元素上回去(preserve状态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 07:04