【问题标题】:how to interval call with parameter angularjs如何使用参数angularjs间隔调用
【发布时间】:2017-11-08 16:14:30
【问题描述】:
如何$interval调用带参数的函数
$interval( getrecordeverytime(2), 100000);
function getrecordeverytime(contactId)
{
console.log(contactId + 'timer running');
}
【问题讨论】:
标签:
angularjs
angularjs-directive
angularjs-ng-repeat
【解决方案1】:
您可以从$interval的第五个参数开始传递参数:
angular.module('app', []).controller('ctrl', function($scope, $interval){
function getrecordeverytime(contactId, second) {
console.log(`${contactId}, ${second} timer running`);
};
$interval(getrecordeverytime, 1000, 0, true, 2, 5);
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl'>
</div>
【解决方案2】:
试试这个。
function getrecordeverytime(contactId){
console.log(contactId + 'timer running');
}
$interval(function(){getrecordeverytime(2)},100000);
【解决方案3】:
或者,您可以创建一个返回间隔回调函数的函数,并通过闭包将参数绑定到回调。像这样:
function createRecordCallback(contactId){
return function(){
console.log(contactId + 'timer running'); // the value of contactId, will be bound to this function.
};
}
$interval(createRecordCallback(1234), 100000);
这只是作为一种选择。在大多数情况下,我确实推荐 Slava 的答案。