$scope 变量在回调函数中没有改变,angularjs

$scope variable doesn't change in callback function, angularjs

我想在函数 one 运行 期间将微调器显示到按钮中,完成后隐藏微调器,这是我尝试过的:

<div ng-controller="MyController">       
        <button ng-click="InsertData()">

            <i class="fa fa-refresh fa-spin" ng-show="loading"></i>Loading
        </button>
        <br />
        {{loading}}
    </div>

这是controller.js

angular.module('MyApp', []).controller('MyController', function ($scope) {

$scope.InsertData=function()
{
    $scope.loading = true;
    $scope.one($scope.two);

}

$scope.one = function (callback) {

    setTimeout(function () { alert("this is function one"); callback(); }, 1000);

}

$scope.two = function () {
    alert("two");
    $scope.loading = false;

}

});

但是这一行

$scope.loading = false;

不执行!虽然上面的行运行,我的意思是 alert("two") 出现了!

为什么$scope.loading的值在回调函数中没有变化?如何解决这个问题?

问题是因为您正在使用 setTimeout 这是一个 Javascript 函数,这会导致问题,其中范围变量不会在范围内更新。因此我们必须为此使用 angular 包装器,即 $timeout().

更多详情here, to know the difference between $timeout() and setTimeout() refer


下面是问题的有效 fiddle。

JSFiddle Demo