如何在AngularJS的同时运行两个控制器

时间:2015-04-29 08:59:02

标签: angularjs

我正在使用AngularJS制作一个webapp(使用Yeoman),我有一个循环,每秒向一个计数器添加1。这很好,直到我需要多个控制器的多个选项卡。我尝试在主控制器中运行循环,但这不起作用。

我希望MoneyCtrl中的gameLoop功能一直运行,有没有更好的地方放置这个功能?

有没有人知道如何做到这一点,或者至少达到同样的效果?

Github project

1 个答案:

答案 0 :(得分:0)

您可以将gameLoop功能放在run块上。

angular.module('incrementalApp', ['ngAnimate', 'ngCookies', 'ngResource',
    'ngRoute', 'ngSanitize', 'ngTouch'
]).config(function($routeProvider) {
    //...
}).run(function($rootScope, MoneyService, Vars){

    var stop;

    $rootScope.loop = function() {
        if (angular.isDefined(stop) ) {
            return;
        }
        stop = $interval(function() {
            angular.forEach(Vars.clickers, function(clicker){
                MoneyService.addMoney((clicker.amount * clicker.production)/Vars.fps);
            });

        }, 1000/Vars.fps);

        $rootScope.stopLoop = function() {
            if (angular.isDefined(stop)) {
                $interval.cancel(stop);
                stop = undefined;
            }
        };

        $rootScope.$on('$destroy', function() {
          // Make sure that the interval is destroyed too
          $scope.stopFight();
        });
    };  

$scope.loop();
})

并使用服务添加资金,以便您可以在每个控制器上要求服务。