Thomas David Kehoe
Thomas David Kehoe

Reputation: 10930

Angular $emit, $on not working

I'm trying to learn Angular event listening. After a user clicks a button, the controller queries the database and returns a value in the button's handler. I'm having trouble passing this value to the $scope so that other functions can access the data.

First question: is this what event listeners are for? Is there another way to do what I want?

Next question: why doesn't this code work:

app.controller('EmitterCtrl', function($scope) {
  console.log("Emitter controller.");

  $scope.buttonClick = function() {
    console.log("Button clicked!"); // this works
    $scope.$emit('myEvent', 'Clicked!'); // child $scope
  };

  $scope.$on('myEvent'), function(event, data) { // parent $scope
    console.log("I heard it!"); // doesn't work
    console.log(event);
    console.log(word);
  };

});

<div ng-controller="EmitterCtrl">
  <button type="button" ng-click="buttonClick()">
    Click me!
  </button>
</div>

The user clicks the button, the event handler fires in the controller. The handler creates a child $scope so $emit sends the event to the parent $scope. Then the event isn't emitted, or the listener doesn't catch it.

Upvotes: 2

Views: 1804

Answers (1)

Ghazanfar Khan
Ghazanfar Khan

Reputation: 3718

$emit dispatches an event upwards ... $broadcast dispatches an event downwards

Detailed explanation

$rootScope.$emit only lets other $rootScope listeners catch it. This is good when you don't want every $scope to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them.

$rootScope.$broadcast is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it.

$scope.$emit is when you want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear).

$scope.$broadcast is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.

Upvotes: 5

Related Questions