angular.module('telavox.test', []) .factory('MySimulatedSlowHTTPService', function($q, $timeout, $rootScope) { var myservice = {}; myservice.refresh = function() { $timeout(function() { // Simulated slow fetch from an HTTP server var randomnumber=Math.floor(Math.random()*11) var randomLengthList = ['Item 1'] for (var i=0; i < randomnumber; i++) { randomLengthList = randomLengthList.concat(randomLengthList) } $rootScope.$broadcast('newList', randomLengthList); }, 3000); } myservice.refresh(); return myservice; }) .controller('MyListLengthAddedController', function($scope, $timeout, MySimulatedSlowHTTPService) { $scope.watchCallbackCalls = 0; $scope.$on('newList', function(ev, mylist) { $scope.watchCallbackCalls++; $scope.myListLengthAdded = mylist.length + 1; }); $timeout(function() { MySimulatedSlowHTTPService.refresh(); }, 10000); }) .controller('MyListLengthController', function($scope, MySimulatedSlowHTTPService) { $scope.$on('newList', function(ev, mylist) { ev.stopPropagation(); $scope.myListLength = mylist.length; }); });
<div ng-app="telavox.test"> <div> <div class="controller" data-ng-controller="MyListLengthAddedController"> If I added one element, the list length would be {{myListLengthAdded}}.<br/> My watch callback was called {{watchCallbackCalls}} times. </div> <div class="controller" data-ng-controller="MyListLengthController"> My current list length is {{myListLength}}. </div> </div> </div>
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script> <style> .error { color: red; } .controller { border: thin solid green; padding: 0.3em; margin: 0.3em; }