我想在函数$ interval中获取值,并将其用作间隔时间。
我有index.html
:
<iframe src="{{MediaFile}}" frameborder="0" allowfullscreen autoplay></iframe>
和MediaFile
表:
+------+-------------+--------------+
| ID | FileName | Interval | //Interval in secs
+------+-------------+--------------+
| 1 | image.jpg | 30 |
+------+-------------+--------------+
| 2 | image1.jpg | 10 |
+------+-------------+--------------+
| 3 | video.mp4 | 50 |
+------+-------------+--------------+
还有index.js
:
// loadMediaFile, select the list of MediaFile in my table
loadMediaFile.MediaFiles('loadMediaFile').then(function (d) {
$scope.IntervalTime = 2000;
$scope.Count = -1;
$interval(function () {
$scope.Count++
$scope.MediaFile = '/MediaFiles/Content/' + d[$scope.Count].FileName;
$scope.IntervalTime = d[$scope.Count].Interval * 1000;
// This is to load back to index 0 of my MediaFile when all is loaded
if (d.length == ($scope.Count + 1)) {
$scope.Count = -1;
}
}, $scope.IntervalTime);
console.log($scope.IntervalTime);
})
输出应为:
Displays Image.jpg after 2secs
Displays Image1.jpg after 30
Displays Video.mp4 after 10
Displays Image.jpg after 50secs
问题在于间隔停留在2秒,它没有更新间隔值,因为正确的值在我的$ interval内。这就是为什么我想要像使用return
一样将正确的值返回到$ scope.IntervalTime的原因。
答案 0 :(得分:1)
您应将$timeout
与递归调用一起使用,而不要使用$interval
:
angular.module('app', []).controller('ctrl', function($scope, $timeout) {
$scope.IntervalTime = 2000;
$scope.Count = 0;
(function timeoutFn() {
$timeout(function() {
$scope.IntervalTime = (($scope.Count++) + 10) * 1000;
console.log($scope.IntervalTime)
timeoutFn();
}, $scope.IntervalTime);
})()
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<div ng-app='app' ng-controller='ctrl'>
</div>
答案 1 :(得分:0)
您的代码工作正常。.只需添加console.log()
$scope.IntervalTime = 2000;
$scope.Count = 0
$interval(function () {
$scope.IntervalTime = (($scope.Count++) + 10) * 1000;
console.log("called :- "+$scope.IntervalTime);
$scope.getValue($scope.IntervalTime);
}, $scope.IntervalTime);
$scope.getValue = function(tt){
console.log("get value outside :- "+tt);
};
console.log("first time called :- "+$scope.IntervalTime);
答案 2 :(得分:0)
如果您希望第一个console.log
显示11000
,请在变量之前前放置增量运算符(++
):
̶$̶s̶c̶o̶p̶e̶.̶I̶n̶t̶e̶r̶v̶a̶l̶T̶i̶m̶e̶ ̶=̶ ̶(̶(̶$̶s̶c̶o̶p̶e̶.̶C̶o̶u̶n̶t̶+̶+̶)̶ ̶+̶ ̶1̶0̶)̶ ̶*̶ ̶1̶0̶0̶0̶;̶
$scope.IntervalTime = ((++$scope.Count) + 10) * 1000;
angular.module('app', [])
.controller('ctrl', function($scope, $timeout) {
$scope.IntervalTime = 2000;
$scope.Count = 0;
timeoutFn();
function timeoutFn() {
$timeout(function() {
$scope.IntervalTime = ((++$scope.Count) + 10) * 1000;
console.log($scope.IntervalTime)
timeoutFn();
}, $scope.IntervalTime/10);
}
})
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app='app' ng-controller='ctrl'>
Count={{Count}}<br>
IntervalTime={{IntervalTime}}
</div>