【问题标题】:AngularJS. Clear $timeout when invoking angular-ui modalAngularJS。调用 angular-ui 模态时清除 $timeout
【发布时间】:2014-01-27 22:04:27
【问题描述】:

我在模态控制器中有几个$timeout 表达式

App.controller('ModalCtrl', function ($scope, $timeout) {
    for (var i = 0; i < 10; i++) {
        (function () {
            var timer = $timeout(function () {
                console.log('timer')
            }, 1000);
        })()
    }
})

调用modal时需要清空所有定时器:

App.controller('MainCtrl', function ($scope, $modal, $timeout) {
    $scope.showMap = function () {
        var modal = $modal.open({
            templateUrl: 'modalap.html',
            controller: 'modalCtrl',
        })

        modal.result.then(function () { //fires when modal is resolving
        }, function () { //fires when modal is invoking
        });
    } })

我该怎么做?

PS 抱歉代码格式错误。我不知道为什么,但我不能更好地格式化它。我复制了代码here

【问题讨论】:

  • 你怎么能注入这样的控制器?

标签: javascript angularjs timeout angular-ui


【解决方案1】:

$timeout 服务返回一个Promise 对象,可用于取消超时。

// Start a timeout
var promise = $timeout(function() {}, 1000);

// Stop the pending timeout
$timeout.cancel(promise);

要取消所有未决的超时,您需要维护一个承诺列表,并在打开模式时取消完整列表。

【讨论】:

    【解决方案2】:

    您也可以通过这样做让他们取消自己...

    (function(){
      var timer = $timeout(function(){
        console.log(timer.$$timeoutId);
        $timeout.cancel(timer);
      }, 1000);
    })();
    

    【讨论】:

    • 这对我来说没有意义。为什么要取消已经调用的$timeout
    • 我想知道 Angular 是否会在超时时保持监听器。看起来是这样,因为如果您调用大量超时,内存会不断增长并最终导致内存泄漏。
    • 我猜你很可能会这样做。
    • @pixelfreak 因为我们可以而且它是免费的!
    猜你喜欢
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    相关资源
    最近更新 更多