2015-03-31 12 views
1

我有兩個事件:

$rootScope.$broadcast('cfpLoadingBar:started'); 
$rootScope.$broadcast('cfpLoadingBar:completed'); 

我怎樣才能「在我的控制器」使用這些事件來打開和關閉一個名爲「加載」屬性的狀態?

+0

您可以使用'$ on'來收聽廣播事件 – mohamedrias 2015-03-31 17:12:20

回答

1

你要聽使用$on

$scope.$on('cfpLoadingBar:started', function(event, data) { 
    // turn on that value 
}); 

類似的這種情況下,

$scope.$on('cfpLoadingBar:completed', function(event, data) { 
     // turn off the value 
    }); 

DEMO:

angular.module("app",[]) 
 
.controller("MainCtrl", function($scope, $rootScope, $timeout) { 
 
    $timeout(function() { 
 
      $rootScope.$broadcast('cfpLoadingBar:started'); 
 
    }, 1000); 
 
    $timeout(function() { 
 
     $rootScope.$broadcast('cfpLoadingBar:completed'); 
 
    }, 3000); 
 

 
    $scope.$on('cfpLoadingBar:started', function(event, data) { 
 
      $scope.flag = "on"; 
 
    }); 
 
    
 
    $scope.$on('cfpLoadingBar:completed', function(event, data) { 
 
    $scope.flag = "off"; 
 
    }); 
 

 
});
<!DOCTYPE html> 
 
<html ng-app="app"> 
 
<head> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script> 
 
    <meta charset="utf-8"> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body ng-controller="MainCtrl"> 
 
<h1>Flag : {{flag}}</h1> 
 
</body> 
 
</html>

相關問題