Melina Melina - 6 months ago 11
AngularJS Question

How can I send an object with $broadcast?

I have the following:

$scope.$watch('tableForm.$pristine', function (newValue) {
$rootScope.$broadcast("tableDataUpdated",
{ state: $scope.tableForm.$pristine });
});


I also tried:

$scope.$watch('tableForm.$pristine', function (newValue) {
var tableForm = { pristine: $scope.tableForm.$pristine };
$rootScope.$broadcast("tableDataUpdated", tableForm);
});


When the tableForm
$pristine
state changes then the value of
$scope.tableForm.$pristine
is set to
False
and this message is broadcast.

However when I try to receive the message the value of "state" is not defined:

$rootScope.$on("tableDataUpdated", function (args) {
alert(args.state);
});


I also tried:

$rootScope.$on("tableDataUpdated", function (args) {
alert(args.tableForm);
});


Still I seem not to be able to send the object and have it received

Answer

That's because listener function has two arguments being passed into it, event, and args. See the angular docs.

Try:

$rootScope.$on("tableDataUpdated", function (event, args) {
        alert(args.state);
    });
Comments