angularjs - How can I use a $broadcast start / stop event to toggle a field between true and false? -
i have 2 events:
$rootscope.$broadcast('cfploadingbar:started'); $rootscope.$broadcast('cfploadingbar:completed'); how can "in controller" use these events toggle on , off state of property called "loading" ?
you need listen event using $on
$scope.$on('cfploadingbar:started', function(event, data) { // turn on value }); similarly,
$scope.$on('cfploadingbar:completed', function(event, data) { // turn off 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>
Comments
Post a Comment