0

我尝试在视图和模态中获取相同的定时器。 用相同的范围这两个工作:示波器角度模态和角度定时器指令

$scope.openTimer = function() { 
var modalInstance = null; 
modalInstance = $modal.open({ 
    templateUrl: 'modal-timer.html', 
    controller: 'ModalTimerController', 
    scope: $scope, 
    backdrop: 'static', 
    size: "sm" 
}); 
modalInstance.result.then(function() { 
    console.log('onCloseModal'); 
}); 
} 

这是我plunker

我遇到的问题是我无法在视图和模态之间共享运行时间(来自定时器指令)。模态总是以重置计时器打开。

有什么办法可以在视图和模态中共享完全相同的定时器运行时间吗?

回答

0

您可以为您的计时器功能使用服务。

https://docs.angularjs.org/guide/services

我将所有的在你的范围从功能到服务,然后只使用范围,以显示当前时间。通过这种方式,您可以将服务注入控制器,并且控制器只负责显示信息。一个服务是一个单例,意味着它只有一个实例,它只是传递到你注入的任何地方。因此,它所处的任何状态都将在注入的任何控制器之间共享。

它看起来像这样(其中TimeService目前持有的代码在你的控制器):

controller: ['$scope', '$element', 'TimeService', 
    function($scope, $element, TimeService) { 
    $scope.timeDisplay = TimeService.currentTime; 
    } 
] 

当然,你必须写服务,并将它的计算值赋给currentTime的。

+1

我做了你所说的并使用[this](http://www.bennadel.com/blog/2674-creating-a-reusable-timer-in-angularjs.htm)来帮助我正确实现它。一切正常,我想要。我开始为angular [here](http://louisamoros.github.io/angular-timer/#/home)实现其他指令/服务计时器。 –