更好的设计,可以将数据传递到其他 ng-view 并将其保留在控制器之间

2024-01-22

我开始使用 AngularJS 进行开发。我很困惑这是否是在我的部分视图之间传递数据的正确设计。

现在我有一个加载程序页面,我可以在其中执行一些请求。

function PeopleController($scope,$http,$location){
    $http.get('/location/-79.18925/43.77596').
    success(function(data){
      $scope.savePeopleResponse(data);
      $location.url('/test');
    });
}

然后在为 /test 加载的视图中

我只是打电话

<div ng-controller="resultController">
    <div class="blueitem">{{getResultForPeople()|json}}</div>
</div>

[结果控制器]

    function resultController($scope){
      $scope.getResultForPeople = function(){
     return $scope.getPeopleResponse();
    }
}

并且 savePeopleResponse 和 getResultForPeople 被“缓存”在 rootScope 中

app.run(function($rootScope) {
  var peopleResponse = {};
  $rootScope.savePeopleResponse = function(data) {
   peopleResponse = data;
   console.log(data);
  }

  $rootScope.getPeopleResponse = function(){
    return peopleResponse;
  }
});

现在正如您所看到的,如果该应用程序变得越来越大,这将变得非常混乱。处理数据以便其在控制器之间持久保存的最佳方法是什么?


您可以通过以下方式跨控制器保存数据创建您自己的服务 https://docs.angularjs.org/guide/services#creating-services正如中所描述的这个博客 http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/。您还可以参考这个问题 https://stackoverflow.com/questions/12008908/pass-variables-between-controllers.

在你的情况下,你可以移动你的savePeopleResponse and getPeopleResponse到服务中,然后将该服务注入到您想要访问它的任何控制器中。

angular.module('myApp', [])
    .factory('peopleService', function () {
        var peopleResponse = {};

        return {
            savePeopleResponse:function (data) {
                peopleResponse = data;
                console.log(data);
            },
            getPeopleResponse:function () {
                return peopleResponse;
            }
        };
    });

使用你的控制器是这样的:

function resultController ($scope, peopleService) {
    $scope.getResultForPeople = peopleService.getPeopleResponse;
}

在此代码示例中,请确保包含ng-app="myApp"

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更好的设计,可以将数据传递到其他 ng-view 并将其保留在控制器之间 的相关文章

随机推荐