R.co
R.co

Reputation: 77

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);
    };

Upvotes: 0

Views: 42

Answers (2)

Moumit
Moumit

Reputation: 9530

The problem is you are defining a delegate here .. no call happened till now ..

$scope.$on('event_detail', function (event, args) {
        $scope.id = args;

        // it will work because the $scope.id get populated
        console.log($scope.id); 

});

//$scope.id It is not populated yet .. 
//it will be populated when the broadcast get called
console.log($scope.id); 

If your code look like something below than it will work...

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

});

$rootScope.$broadcast("event_detail", data.id_case); //make the braodcast

console.log($scope.id); // it will be no-more undefined

Upvotes: 0

Tomer
Tomer

Reputation: 17930

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;

Upvotes: 4

Related Questions