admin管理员组文章数量:1356847
I'm trying to push an item to an array every 5 seconds in an AngularJS service, but I keep getting 'items is not defined' after 1 item is added dynamically...
I've been playing with this simple code for over an hour now, I'm sure it's something silly but I can't figure it out. :/
app.service('ItemService', function() {
var items = [9000];
this.addItem = function () {
items.push(Math.random());
}
setInterval(this.addItem(), 5000);
return {
get: function() {
return items;
}
}
});
Plnkr:
I'm trying to push an item to an array every 5 seconds in an AngularJS service, but I keep getting 'items is not defined' after 1 item is added dynamically...
I've been playing with this simple code for over an hour now, I'm sure it's something silly but I can't figure it out. :/
app.service('ItemService', function() {
var items = [9000];
this.addItem = function () {
items.push(Math.random());
}
setInterval(this.addItem(), 5000);
return {
get: function() {
return items;
}
}
});
Plnkr: http://plnkr.co/edit/EVFUww7dfUAJzQqth7mx
Share Improve this question asked Feb 17, 2015 at 8:50 user1960364user1960364 2,0096 gold badges29 silver badges48 bronze badges 3-
try
this.items.push()
... – Rakesh_Kumar Commented Feb 17, 2015 at 8:52 - 1 @SearchAndResQ why is that wrong? its a new array with 9000 in it? – Chris Charles Commented Feb 17, 2015 at 8:54
- @SearchAndResQ - It isn't wrong - It creates an array with one item at index:0 with value 9000. – techfoobar Commented Feb 17, 2015 at 8:54
4 Answers
Reset to default 4You're using angular, so you shouldn't be doing setInterval
, but rather use the $interval
service provided by Angular.
That, coupled with the correct observation of @techfoobar, would result in the correct behavior you are looking for:
app.service('ItemService', ['$interval', function($interval) {
var items = [9000];
this.addItem = function () {
items.push(Math.random());
}
$interval(this.addItem, 5000);
return {
get: function() {
return items;
}
}
}]);
Working Plunker.
You are calling addItem()
and passing its return value to setInterval()
- instead of the function itself.
It should be:
setInterval(this.addItem, 5000); // no () after addItem
try using $interval() service instead of setInterval
$interval($scope.item, "time_interval");
Timing function like window.setInterval, in angularjs are wrapped in $interval (https://docs.angularjs/api/ng/service/$interval). Angular manages interval function like a promise to ensure more control over timer.
本文标签: javascriptUncaught ReferenceError items is not definedStack Overflow
版权声明:本文标题:javascript - Uncaught ReferenceError: items is not defined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743952288a2567505.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论