user2175281
user2175281

Reputation: 53

AngularJS Service Variable Reference

I've been scratching my head for days over this, and excuse my lack of JavaScript expertise as that may be the problem.

I have an Angular application that, among other things, has a Queue of items a user will work. I have a Service that manages this queue (current item, move, complete, etc.). The controller I created fetches the current queue item's details from the server, then displays them.

The issue I'm having is the Service is correctly moving through the Queue of objects, setting the current item to the array item at the current index. However, the Controller never sees the current item change.

Here is a basic example for explanation. A working example is at http://jsfiddle.net/Surefire_gf/pjMrh/2/, you'll need to view console to see output.

// ... service code...
var items = [];
var currentItem;
var currentIndex;
...
var moveNext = function() {
    currentIndex = currentIndex + 1;
    currentItem = items[currentIndex];
};

// ... controller code ...
var skip = function() {
    service.moveNext();
    fetchData(service.currentItem);  //THIS NEVER CHANGES, ALWAYS UNDEFINED
};

Setting the current item variable to a position in the array is seen within the service, but never the controller. However, if I do an angular.extend instead of directly referencing the array, it works. Does anyone know what might be going on?

Upvotes: 3

Views: 6598

Answers (2)

zs2020
zs2020

Reputation: 54551

You got a variable scope issue such that the variable currentItem get released after the function execution scope ends. Assigning currentItem to this will fix it.

var moveNext = function () {
    ...
    this.currentItem = items[currentIndex];
    ...
};
return {
    currentItem: this.currentItem,
    moveNext: moveNext
};

DEMO

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 220176

That's because the service object is never updated from within your moveNext function.

Try this:

// service code...
var service = {
    currentItem: null
};

// .......

service.moveNext = function () {
    currentIndex = currentIndex + 1;
    if (currentIndex >= items.length) {
        currentIndex = 0;
    }
    service.currentItem = items[currentIndex];
//  ^^^^^^^^ this is what was wrong...
};

return service;

Here's your fiddle: http://jsfiddle.net/pjMrh/3/

Upvotes: 2

Related Questions