Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

angularjs - Better design for passing data to other ng-view's and persisting it across controllers

I started developing in AngularJS. I'm confused as to whether this is a proper design to pass data between my partial views.

Right now I have a loader page where I do some request.

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

Then in the view that gets loaded for /test

I am just calling

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

[resultController]

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

and the savePeopleResponse and getResultForPeople are "cached" in the rootScope as such

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

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

Now as you can see, this will get very messy if this application grows larger and larger. What's the best way to handle data so that it's persisted across controllers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can persist data across controllers by creating your own service as described nicely in this blog. You can also refer to this question.

In your case you can move your savePeopleResponse and getPeopleResponse into a service and then inject the service into any controllers you would like to access it.

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

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

With your controller something like this:

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

With this code example make sure you include ng-app="myApp"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...