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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for. Thanks Yuri.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.