Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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
–
You'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
Timing function like window.setInterval, in angularjs are wrapped in $interval (https://docs.angularjs.org/api/ng/service/$interval).
Angular manages interval function like a promise to ensure more control over timer.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.