【问题标题】:AngularJS: How do I insert window.setTimeout into the scope function?AngularJS:如何将 window.setTimeout 插入范围函数?
【发布时间】:2015-12-18 17:36:24
【问题描述】:
$scope.runTest = function() {
    var statesArray = ['Running', 'Complete', 'Rejected'];
    var rand = statesArray[Math.floor(Math.random() * statesArray.length)];
    item.state = 'Running';
    console.log(rand)
    window.setTimeout(function() {
        item.state = rand;
    }, 6000);
};

item 状态更改为Running 成功,但之后状态不会更改为window.setTimeout 函数中所述的随机状态。

我哪里错了?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    你应该使用 Angular 的 $timeout service

    $timeout(function() {
        item.state = rand;
    }, 6000);
    

    【讨论】:

      【解决方案2】:

      Windows.setTimeout 在角度范围之外

      您必须使用$scope.$apply() 来绑定该值。

      或使用$timeout

      参考这个What advantage is there in using the $timeout in Angular JS instead of window.setTimeout?

      【讨论】:

        【解决方案3】:

        您可以使用setTimeout$timeout,这里的问题是您在使用setTimeout 时忘记调用scope.apply() 以确保对范围的任何更改都会反映在其他地方。

        setTimeout(function () {
            $scope.$apply(function () {
                item.state = rand;
            });
        }, 6000);
        

        如果您使用$timeout,则不需要使用$scope.$apply()

        $timeout(function() {
            item.state = rand;
        }, 6000);
        

        有关这两个概念的更多信息,请查看What advantage is there in using the $timeout in Angular JS instead of window.setTimeout?

        【讨论】:

          猜你喜欢
          • 2013-10-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-09
          • 2019-07-16
          • 1970-01-01
          • 2014-01-26
          相关资源
          最近更新 更多