0

How do I broadcast a message between controllers?

Here is what I have tried:

function Ctrl1($scope) {
    $scope.$broadcast('Update');
}

Ctrl1.$inject = ['$scope'];

function Ctrl2($scope) {
    $scope.updated = false;
    $scope.$on('Update', function () {
        $scope.updated = true;
    });
}

Ctrl2.$inject = ['$scope'];

To see it running: view the Plnkr.

Foo Stack
  • 2,185
  • 7
  • 24
  • 25

2 Answers2

1

Instead of using $broadcast() a shared service and $watch() might be a better alternative.

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

myApp.factory("MyService", function () {
    return {
        updated: false
    };
});

function Ctrl1($scope, MyService, $timeout) {
    $timeout(function () {  //Some work occurs and sets updated to true

        MyService.updated = true;

    }, 1000)
}

Ctrl1.$inject = ['$scope', "MyService", "$timeout"];

function Ctrl2($scope, MyService) {
    $scope.$watch(function () {
        return MyService.updated;
    }, function (oldValue, newValue) {
        $scope.updated = MyService.updated;
    });
}

Ctrl2.$inject = ['$scope', "MyService"];

Updated Plnkr

Mark Coleman
  • 40,542
  • 9
  • 81
  • 101
0

It depends on the scopes hierarchy and therefore on where you bootstrap your Ctrl1 and Ctrl2 in your dom.

Say Ctrl1 is the parent of Ctrl2. $broadcast will transmit the event to child scopes: Ctrl2 in this case will notice it (use $on).

If you need to transmit an event from Ctrl2 to Ctrl1, use $emit that transmit the event to parent scopes.

ocolot
  • 718
  • 6
  • 18