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.