简体   繁体   English

一个人如何同时运行两个控制器AngularJS

[英]How would one run two controllers at the same time AngularJS

I'm making a webapp in AngularJS (using Yeoman), and I have a loop to add 1 to a counter every second. 我正在使用AngularJS(使用Yeoman)制作一个webapp,我有一个循环,每秒向计数器添加1。 This worked fine, until I needed multiple tabs with multiple controllers. 在我需要带有多个控制器的多个选项卡之前,此方法运行良好。 I tried running a loop in the main controller, but this didn't work. 我尝试在主控制器中运行循环,但这没有用。

I want the gameLoop function in MoneyCtrl to run at all times, is there a better place to put this function? 我希望MoneyCtrl中的gameLoop函数始终运行,是否有更好的放置此函数的地方?

Does anyone have an idea of how I could do this, or at least achieve the same effect? 有谁知道我该怎么做,或者至少达到相同的效果?

Github project Github项目

You can put the gameLoop function on the run block. 您可以将gameLoop函数放在运行块上。

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();
})

And use a service to add the money so you can require the service on each controller. 并使用一项服务来充值,以便您可以在每个控制器上都需要该服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM