R.co R.co - 1 year ago 62
AngularJS Question

Access variable set in event

Is there any way to access a variable set in event ?

the code :

$scope.$on('event_detail', function (event, args) {
$scope.id = args;
console.log($scope.id); // it works

console.log($scope.id); // it says undefined

If I try to display in console "$scope.id", the console says "undefined".
I want to access the variable out of the function event $scope.$on

my broadcast :

$scope.showDetail = function (data) {
$rootScope.$broadcast("event_detail", data.id_case);
$location.path("/detailcase/" + data.id_case);

Answer Source

The problem is that $scope.$on is async so when you call console.log outside the event function, $scope.id was not set yet.

So you have to do whatever you want to do inside the $on function, because then you know for sure that $scope.id has been populated;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download