当我触发功能时,ng-show不会改变

时间:2015-01-12 09:03:41

标签: angularjs

有人可以解释为什么spinerChange()函数无法正常工作吗? http://jsfiddle.net/HB7LU/9907/

<div ng-controller="naujienosControler">
<button type="button" ng-click="spinerButtonChange()">Click Me!</button>
<div class="spinner" ng-show="spiner" >
    <div class="cube1"></div>
    <div class="cube2"></div>
</div>
</div>


var myApp = angular.module('myApp',[]);
myApp.controller('naujienosControler', function ($scope) {

var status = true;
$scope.spiner = status;
$scope.spinerButtonChange = function(){$scope.spiner = !$scope.spiner;};    
function spinerChange(){

setTimeout(function(){ alert("Why spiner dont disapear?????????"); $scope.spiner = false;},      3000);
console.log($scope.spiner);

};

spinerChange();
});

3 个答案:

答案 0 :(得分:2)

注入并使用$timeout,因为您希望角度在执行操作后执行digest

myApp.controller('naujienosControler', function ($scope, $timeout){   
    $timeout(function(){ $scope.spiner = false; }, 3000});
}

编辑(感谢lechariotdor):使用“angularjs world”包装器总是一个好习惯,因为它们运行$apply方法,在您的范围内执行digest并“同步”模型发生的变化。

答案 1 :(得分:1)

因为javascript setTimeout是一个不在angularjs范围内触发的事件,所以angular不知道范围之外的变化。

有一种方法可以使用$timeout代替setTimeout,如下所示,这里是DOC for $timeout

$timeout(function() {
    $scope.spiner = !$scope.spiner;
}, 3000)

并且不要忘记将$timeout注入控制器,

myApp.controller('naujienosControler', function ($scope, $timeout) {....

这里是the update


使用$scope.$appy() here is a good tutorial about $apply()

还有另一种选择
function spinerChange(){    
    setTimeout(function(){
        $scope.spiner = !$scope.spiner;
        $scope.$apply();    
    }, 3000);
    };    
    spinerChange();
});

function spinerChange(){    
    setTimeout(function(){        
        $scope.$apply(function() {
            $scope.spiner = !$scope.spiner;
        });    
    }, 3000);
    };    
    spinerChange();
});

答案 2 :(得分:0)

使用: -

$timeout(function(){ alert("Why spiner dont disapear?????????"); $scope.spiner = false;}, 500);