3

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?

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

In my original fiddle, the value was set on line 29, currentItem = items[currentIndex]; Excuse my JavaScript ignorance, but why didn't that work?
@user2175281 - In your original fiddle, currentItem is just a local variable; it's not part of the service (even though you assigned its value to the service object).
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.