arun kamboj
arun kamboj

Reputation: 1315

How can i broadcast my factory result to other controller

I want to broadcast my result from one controller to another, I have a IntroController where i call article Service factory. after getting response from article factory i want to broadcast its result to Article Ctrl (article controller) but i am unable to broadcast the result to Article Ctrl (article controller).

// Intro Ctrl code here

    angular.module('starter.controllers')
    .controller('IntroCtrl', function($scope, $state, $ionicSlideBoxDelegate,$q,articleService,$rootScope) {
          articleService.getArticles().then(function(res) {
             $rootScope.$broadcast('articleFetch', res);
              $scope.$emit('articleFetch', res);
            }, function(err) {
                alert("error");

            });

    });

// articleService factory code here


angular.module('starter.controllers')
.factory('articleService', function ($http, $q) {
    return {
            getArticles: function() {
            var deferred = $q.defer();
                $http({
                    url: "my-link.com/secure-mobile/getallinfo?access_token=b8fa2380632307d58834d037d7dc65fc",
                    data: { starLimit: 0, endLimit: 100,created_date: 0 },
                    method: 'POST',
                    withCredentials: true,
                }).success(function (data, status, headers, config) {
                    deferred.resolve(data);
                }).error(function (err) {
                 deferred.resolve(0);
                })
                return deferred.promise;
            }

    }
});

I want to broadcast this articleService result(i.e res) to ArticleCtrl controller.

 // ArticleCtrl code here

    angular.module('starter.controllers')
      .controller('ArticleCtrl', function($scope,$rootScope) {
          alert("fff");
            $rootScope.$on('articleFetch', function (event, args) {

                    alert(args);
            $scope.articles = args;

            });
     });

when i call $rootScope.$on in ArticleCtrl then i am not getting alert.

Any Idea?

Upvotes: 0

Views: 394

Answers (1)

aorfevre
aorfevre

Reputation: 5064

You can use $rootScope.$broadcast to broadcast your event and into your second controller $scope.$on to catch the event

It seems that you did it properly. However, for this to work, both controllers MUST be already loaded.

Is it the case ? If not, then you can't catch an event into a non existing controller ;)

Upvotes: 3

Related Questions