user1037355
user1037355

Reputation:

how to listen to broadcast event in angular?

I found this example: http://jsfiddle.net/eshepelyuk/vhKfq/ that has one controller triggering an event and another listening for it..

I have been attempting to get this setup on my own small group of controllers but i keep getting a reference error when i try to fire off the event. I am trying to fire the event right down at the bottom if the response from the server was a success...

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

I am clearly trying to inject the shared service incorrectly but not sure what i am doing wrong.

This is the full error output:

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)

Upvotes: 1

Views: 9070

Answers (2)

engincancan
engincancan

Reputation: 2472

I highly recommend the Angular Style Guide of John Papa. There are best practices on his post. Separating anonymous function to named function is better solution.

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'];

Upvotes: 6

Tasfiqul Ghani
Tasfiqul Ghani

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

I would have the directive call a method on the controller, which is specified in the HTML where the directive is used:

For a directive that uses an isolate scope:

Upvotes: -3

Related Questions