<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="App">
<h1>Broadcast AngularJS port</h1>
<div ng-controller="parent">
this is parent controller.
<button id="action" ng-click="action()">action</button>
<button ng-click="profileAction()">profile action</button>
<div ng-repeat="item in items" ng-controller="child">
<h3>child controller {{$index}}</h3>
</div>
</div>
<script src="https://rawgit.com/bahmutov/console-log-div/master/console-log-div.js"></script>
</body>
</html>
var randomMillis = function() {
return Math.floor(Math.random() * 5000);
}
angular.module('App', [])
.controller('parent', function ($scope, $q) {
$scope.items = ['one', 'two', 'three'];
var defer;
$scope.action = function action() {
$scope.actionStarted = 0;
$scope.$broadcast('action');
console.log('parent sent action broadcast');
defer = $q.defer();
return defer.promise;
};
$scope.$on('actionStarted', function () {
$scope.actionStarted += 1;
});
$scope.$on('actionCompleted', function () {
$scope.actionStarted -= 1;
console.log('remaining actions', $scope.actionStarted);
if ($scope.actionStarted === 0) {
defer.resolve();
}
});
$scope.profileAction = function profileAction() {
var _action = $scope.action;
$scope.action = function () {
console.profile('action');
console.time('action');
$q.when(_action())
.finally(function () {
console.timeEnd('action');
console.profileEnd('action');
$scope.action = _action;
});
};
};
})
.controller('child', function ($scope, $timeout) {
$scope.$on('action', function childAction() {
var ms = randomMillis();
console.log('starting action in child for', ms, 'ms');
$scope.$emit('actionStarted');
$timeout(function () {
console.log('action completed after', ms, 'ms');
$scope.$emit('actionCompleted');
}, ms);
});
});
/* Styles go here */