setTimeout()无法在angularjs中工作?

时间:2015-05-26 23:02:13

标签: javascript html angularjs

AngularJS新手。想知道为什么setTimeout不起作用。它是否真的与SnularJS合作?

jsfiddle.net

<div ng-controller="MyCtrl">
    <select ng-model='form'  ng-options='option.value as option.name for option in typeOptions'></select>
</div>
<script>
var myApp = angular.module('myApp',[]);


function MyCtrl($scope) {

    //$scope.typeOptions = [];
    alert("hi23");
    $timeout(function() {
        alert("hi");
        $scope.typeOptions =
    [
    { name: 'Feature', value: 'feature' }, 
    { name: 'Bug', value: 'bug' }, 
    { name: 'Enhancement', value: 'enhancement' }
    ]; 
     $scope.form =  $scope.typeOptions[1].value;                     
    }, 3000);


}
</script>

感谢。

2 个答案:

答案 0 :(得分:6)

你需要注入$timeout。请注意以下更改

function MyCtrl($scope, $timeout) { 
    ....
}

有关详细信息,请参阅$timeout docs

此外,不建议使用这种声明控制器。我鼓励重新分析以下内容......

myApp.controller('MyCtrl', ['$scope', '$timeout', function($scope, $timeout) {
    .... 
}]);

答案 1 :(得分:2)

Angular有一个观察者列表,它是将视图与其模型绑定在一起的所有变量和对象。 Angular会一直监听更改其中任何内容的事件,并启动摘要周期以使用新值更新DOM。

当你使用setTimeout时,它会以异步方式运行,并且Angular不会监视setTimeout中的所有代码,即使它可能正在改变其中一个Angular范围值。

所以你可以按照上面的建议使用$ timeout,也可以将你的setTimeout代码包装在$ scope中。$ apply,告诉Angular也要注意它。

对于您在Angular应用程序中使用的任何外部Jquery库,这也是一个很好的做法。虽然推荐的方法是对这些库使用Angular包装器。

相关问题