2016-06-07 56 views
0

有什么方法可以访问事件中设置的变量吗?事件中设置的访问变量

代码:

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

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

如果我尝试在控制台上显示 “$ scope.id”,控制台说 “不确定”。 我要访问的变量out功能事件$范围$上

我的广播:

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

是,如果$ broadcast/$ emit具有参数:$ broadcast(name,args);.你的$ broadcast/$发射是什么样的? – Brian

+0

好的,我会更新 –

回答

4

的问题是,$scope.$on是异步,所以当你调用console.log事件功能外,$scope.id是尚未设置。

所以你必须在$on函数中做任何你想做的事情,因为那样你肯定知道$scope.id已经被填充;

+0

好的,谢谢。 –

+0

很好,完全错过了那个。 – Brian

0

问题是你要定义一个delegate这里..没有呼叫发生到现在..

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

如果你的代码看起来像下面比它会工作的东西...

$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