如何将我的工厂结果广播到其他控制器

时间:2015-07-07 12:03:35

标签: angularjs ionic-framework ionic

我想将我的结果从一个控制器广播到另一个控制器,我有一个IntroController,我称之为文章服务工厂。从文章工厂得到回复后,我想将其结果广播到文章Ctrl(文章控制器),但我无法将结果广播到文章Ctrl(文章控制器)。

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

    }
});

我想将这篇文章的服务结果(即res)广播到ArticleCtrl控制器。

 // 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;

            });
     });

当我在ArticleCtrl中调用$ rootScope。$ on时,我没有收到警报。

任何想法?

1 个答案:

答案 0 :(得分:3)

您可以使用$rootScope.$broadcast广播您的活动 并进入你的第二个控制器$scope.$on来捕捉事件

看来你做得很好。 但是,要使其工作,两个控制器必须已经加载。

是这样的吗? 如果没有,那么您无法将事件捕获到不存在的控制器中;)