开发者问题收集

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

2015-05-25
8960

我发现了这个例子: 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个回答

我强烈推荐 John Papa Angular 风格指南 。他的帖子中有 最佳实践 。将匿名函数与命名函数分开是更好的解决方案。

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'];
engincancan
2015-05-25
<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 中指定:

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

Tasfiqul Ghani
2015-05-25