javascriptangularjscontrollerangular-broadcast

$broadcast only firing when limited characters used


Trying to use Angular's $broadcast, when I test it and use the string 'hi', and watch for it in a sibling controller, it works fine, like so:

//first controller
app.controller('colourKeyCtrl', colourKeyCtrl);
function colourKeyCtrl($scope, $timeout, patents, patentPhasesService) {
    vm.$onInit = function() {
       $scope.$broadcast('hi');
    }
}

//second controller
app.controller('graphDonutCtrl', graphDonutCtrl);
function graphDonutCtrl($scope, patents, patentPhasesService, $timeout) {
    $scope.$on('hi', function(event, opt){
       alert('hello there')
    })    
}

As soon as I change the string to anything else, such as phaseChange, it fails to invoke the $on method in the second controller. Not sure why. I have attempted to wrap $broadcast in a $timeout method but that hasn't resolved the issue.

Question

Am I using $broadcast in the wrong manner or is my syntax incorrect?

.state('dashboard', {
    url: '/dashboard',
    views: {
        '@': {
            templateUrl: 'p3sweb/app/components/dashboard/views/dashboard.htm',
            controller: 'dashboardCtrl',
            controllerAs: '$ctrl'
        },
        'colourkeywidget@dashboard': {
            templateUrl: 'p3sweb/app/components/dashboard/views/ui-views/colour-key-widget.htm',
            controller: 'colourKeyCtrl',
            controllerAs: '$ctrl'                
        },
        'graphdonutwidget@dashboard': {
            controller: 'graphDonutCtrl',
            controllerAs: '$ctrl',                
            templateUrl: 'p3sweb/app/components/dashboard/views/ui-views/graph-donut-widget.htm',         
        }
    }
})

Solution

  • $broadcast starts at the current scope and goes down to child scopes.

    $emit starts at the current scope and goes up the scope chain.

    There is no event dispatch method that goes to sibling scopes.You'd need to $emit up to the parent and handle the event there to $broadcast it back down.