user3682511
user3682511

Reputation: 45

AngularJs broadcast event

I want to broadcast angular event from javascript function i.e angular.injector(['ng', 'myModule']).get("mySharedService").prepForBroadcast('hello'); By using above line I can invoke prepForBroadcast() but I can't catch event in $scope.$on()

Note: I want to call prepForBroadcast() method from javascript function.

    <!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <!-- SPELLS -->
  <!-- load angular via CDN -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  <script src="script.js"></script>
  <style>
    .question{
        border:1px solid darkgray;
        padding:10px;
        margin-bottom:10px;
    }
  </style>
</head>
<body>
    <div ng-app="myModule">
        <div id="appID" ng-controller="ControllerZero">
            <input ng-model="message" >
        </div>

        <div ng-controller="ControllerOne">
            <input ng-model="message" >
        </div>

        <div ng-controller="ControllerTwo">
            <input ng-model="message" >
        </div>

        <my-component ng-model="message"></my-component>
    </div>

</body>
<script>
angular.injector(['ng','myModule']).get("mySharedService").prepForBroadcast('hello');
</script>
</html>

script.js file

var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        console.log('prepForBroadcast');
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        console.log('broadcastItem');
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

function ControllerZero($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        console.log('handle event');
        $scope.message = sharedService.message;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}



ControllerZero.$inject = ['$scope', 'mySharedService'];

ControllerOne.$inject = ['$scope', 'mySharedService'];

ControllerTwo.$inject = ['$scope', 'mySharedService'];

Upvotes: 0

Views: 2697

Answers (2)

vinesh
vinesh

Reputation: 4903

Another way of publishing events from one controller and listening them in other controllers would be to use angular-PubSub module.

The PubSub makes only subscribers to listen to the published events unlike the $rootScope.$broadcast in which it sends event to all the Scopes in Scope hierarchy making it inefficient as compared to the PubSub approach.

Upvotes: 0

tasseKATT
tasseKATT

Reputation: 38490

angular.injector() creates a new injector, and with it a new $rootScope. The event will be broadcasted on this new $rootScope instead of on the one your controllers are listening on.

You need to retrieve the injector already associated with your application:

angular.element(domElement).injector();

You also need to manually trigger the digest loop for the data bindings to update, for example by using $apply.

Example:

angular.element(document).ready(function() {

  var element = angular.element(document.querySelector('.ng-scope'));
  var injector = element.injector();
  var scope = element.scope();

  scope.$apply(function() {
    injector.get('mySharedService').prepForBroadcast('hello');
  });
});

Demo: http://plnkr.co/edit/NDKBdzSmvN1xY7alafir?p=preview

Upvotes: 1

Related Questions