如何在角度中听广播事件?

时间:2015-05-25 15:05:11

标签: angularjs

我找到了这个例子:http://jsfiddle.net/eshepelyuk/vhKfq/有一个控制器触发一个事件而另一个控制器正在监听它..

我一直在尝试在我自己的小组控制器上进行此设置,但是当我尝试触发事件时,我一直收到引用错误。如果来自服务器的响应成功,我试图在底部发起事件......

'use strict';

var CommentAppControllers = angular.module('CommentAppControllers', []);

/**
 * Register the shared service
 */
CommentAppControllers.factory('mySharedService', function($rootScope) {
    return {
        broadcast: function(msg) {
            $rootScope.$broadcast('handleBroadcast', msg);
        }
    };
});

/**
 * Get the users own Comments
 */
CommentAppControllers.controller('CommentWallMine', ['$scope', 'MyComments',
    function($scope, MyComments) {
        $scope.myComments = MyComments.query();
        //listen for a new comment via the broadcast system:
        $scope.$on('handleBroadcast', function(event, message) {
            console.log( message );
        });

    }]);

/**
 *  Process the comment submit form
 **/ 
CommentAppControllers.controller('CommentBox', ['$scope', '$http', 'mySharedService',
    function($scope, $http, mySharedService) {
        $scope.form_data = {};
        $scope.server_response = {};
        $scope.error = {};

        $scope.process_form = function(){
            $http({
                method  : 'POST',
                url     : '/api/make-Comment',
                data    : $.param($scope.form_data),  // pass in data as strings
                headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  // set the headers so angular passing info as form data (not request payload)
            })
            .success(function(data) {
                $scope.server_response = data;

                if(!data.success ){
                    $scope.error = data.error_fields;
                } else {
                    //add the data to this user display
                    mySharedService.broadcast('test broadcast');
                }
            });
        }
    }
]);

我显然是在尝试错误地注入共享服务但不确定我做错了什么。

这是完整的错误输出:

ReferenceError: mySharedService is not defined
    at controllers.js:57
    at angular.js:9408
    at processQueue (angular.js:13248)
    at angular.js:13264
    at Scope.$get.Scope.$eval (angular.js:14466)
    at Scope.$get.Scope.$digest (angular.js:14282)
    at Scope.$get.Scope.$apply (angular.js:14571)
    at done (angular.js:9698)
    at completeRequest (angular.js:9888)
    at XMLHttpRequest.requestLoaded (angular.js:9829)

2 个答案:

答案 0 :(得分:7)

我强烈推荐Angular Style GuideJohn Papa。他的帖子中有best practices个帖子。将匿名函数分离到命名函数是更好的解决方案。

var CommentAppControllers = angular.module('CommentAppControllers', []);

/**
 * Register the shared service
 */
CommentAppControllers.factory('mySharedService', mySharedService);

function mySharedService($rootScope) {
    return {
        broadcast: function(msg) {
            $rootScope.$broadcast('handleBroadcast', msg);
        }
    };
}

mySharedService.$inject = ['$rootScope'];


/**
 * Get the users own Comments
 */
CommentAppControllers.controller('CommentWallMine', CommentWallMine);

function CommentWallMine($scope, MyComments) {
    $scope.myComments = MyComments.query();
    //listen for a new comment via the broadcast system:
    $scope.$on('handleBroadcast', function(event, message) {
        console.log(message);
    });

}
CommentWallMine.$inject = ['$scope', 'MyComments'];


/**
 *  Process the comment submit form
 **/
CommentAppControllers.controller('CommentBox', CommentBox);

function CommentBox($scope, $http, mySharedService) {
    $scope.form_data = {};
    $scope.server_response = {};
    $scope.error = {};

    $scope.process_form = function() {
        $http({
                method: 'POST',
                url: '/api/make-Comment',
                data: $.param($scope.form_data), // pass in data as strings
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                } // set the headers so angular passing info as form data (not request payload)
            })
            .success(function(data) {
                $scope.server_response = data;

                if (!data.success) {
                    $scope.error = data.error_fields;
                } else {
                    //add the data to this user display
                    mySharedService.broadcast('test broadcast');
                }
            });
    }
};

CommentBox.$inject = ['$scope', '$http', 'mySharedService'];

答案 1 :(得分:-3)

<div my-dir ctrl-fn="someCtrlFn(arg1)"></div>

app.directive('myDir', function() {
  return {
    scope: { ctrlFn: '&' },
    link: function(scope, element, attrs) {
       ...
       scope.ctrlFn({arg1: someValue});
    }

我会让指令在控制器上调用一个方法,该方法在使用该指令的HTML中指定:

对于使用隔离范围的指令:

相关问题