0

I am looking for best practices with AngularJS: I need to share a json ajax response between nested controllers. Controller1->Controller2->Controller3

Right now I have a working version that simply sets a $scope.variable with the response in controller1, and the other controllers access it by calling the same variable.

I have tried creating a global service, but the problem is I make the ajax call in a controller, and before the ajax call is finished, the global variable defaults to null for all the other controllers.

I am just trying to understand what best approach is in this situation.

Thanks

l2silver
  • 3,283
  • 6
  • 23
  • 28

2 Answers2

1

You can put the value in $rootScope.variable and after access it from any other controller (as $scope.variable)

David Faure
  • 1,336
  • 14
  • 25
1

Create publisher/subscriber service or factory and subscribe methods from your controller2 and 3 to data change. Just like this:

angular
  .module('')
  .factory('GlobalAjaxVariable', function() {
    var subscribers = [];

    function publish(data) {
      callbacks.forEach(function(clb) {
        clb(data);
      });
    }

    return {
      setData: function(ajaxData) {
        publish(ajaxData);
      },

      addSubscriber: function(clb) {
        subscribers.push(clb);
      }
    };
  });
Yuri H.
  • 51
  • 2