0

I'm doing a slider following the steps from this tutorial using Angular.js and Firebase API.

I have created a directive 'slider' in my directive file, here is the code:

.directive('slider', function()
{
    return {
        restrict: 'E',
        replace: true,
        link: function(scope, elem, attrs) {
            scope.currentIndex = 0; // Initially the index is at the first slide

            scope.next = function()
            {
                scope.currentIndex < scope.challenges.length - 1 ? scope.currentIndex++ : scope.currentIndex = 0;
            };

            scope.prev = function()
            {
                scope.currentIndex > 0 ? scope.currentIndex-- : scope.currentIndex = scope.challenges.length - 1;
            };

            scope.$watch('currentIndex', function()
            {
                scope.challenges.forEach(function(challenge)
                {
                    challenge.visible = false; // make every challenge invisible
                });

                scope.challenges[scope.currentIndex].visible = true; // make the current challenge visible
            });
        },
        template: '<div></div>'
    };

I have no isolate scope, as you see, so it should take scope.challenges from parent, but it comes as undefined value instead of the data from Firebase.

So doing forEach of undefined it throws an error: TypeError: Cannot read property 'forEach' of undefined

I spent like 3 hour trying to understand scopes, a solution will be so rewarding. Thank you very much.

Alejandro Garcia Anglada
  • 2,373
  • 1
  • 25
  • 41
  • Can you share the code where challenges is created? You've mentioned firebase so I imagine there are some async ops taking place? – Kato Sep 24 '14 at 20:45
  • Alternative angular.forEach(scope.challenges, function(challenge) { challenge.visible = false }); – DeadCalimero Sep 24 '14 at 21:03
  • @Kato in controller I have `$scope.findAll = function() { $scope.challenges = Challenge.findAll(); };` it just take all the result from Firebase. – Alejandro Garcia Anglada Sep 24 '14 at 21:12
  • @DeadCalimero I have it tried and doesn't work because scope.challenges is still undefined, I have also tried to $watch challenges to check if is it is something asynchronous. – Alejandro Garcia Anglada Sep 24 '14 at 21:14
  • @aganglada is certainly a promise, Challenge.findAll() request an url with $http. Do you resolved the promise before iterate ? – DeadCalimero Sep 24 '14 at 21:16
  • I have also tried doing this promise [solution](http://stackoverflow.com/questions/14619884/angularjs-passing-object-to-directive) – Alejandro Garcia Anglada Sep 24 '14 at 21:48
  • Can you post your challenge controller or the controller where is stored challenges. – DeadCalimero Sep 24 '14 at 21:55
  • It is a few comments above, just defining $scope.challenges = [] as global and then assigning in the findAll function – Alejandro Garcia Anglada Sep 24 '14 at 22:07
  • I'm pretty sure it's an logic problem due to asynchronous, if u post all the code on jsFiddle it's was most easiest to help you sire. – DeadCalimero Sep 24 '14 at 22:19
  • That was what I thought but to check it a put the whole function inside of a setTimeout with 5s and challenges is still undefined, I will prepare a jsFinddle for you all, that way you can check it out. – Alejandro Garcia Anglada Sep 24 '14 at 22:25
  • As mentioned by more than one person now, this is an async issue and you need to provide an [mvce](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378) so we can stop playing whack-a-mole and answer the question directly. – Kato Sep 25 '14 at 14:15

2 Answers2

1

@rizome thank you very much for your answer, it was really useful.

Firebase API returns directly a promise, so you don't have to do so.

Finally I resolve it, updating 'angularfire' to v0.8 and this code:

// Controller code
Challenge.findAll().$asArray().$loaded().then(function(challenges)
{
    $scope.challenges = challenges;
});

Basically what it does is wait till challenges are ready to assign.

This article from firebase was really a good resource to solve it.

Alejandro Garcia Anglada
  • 2,373
  • 1
  • 25
  • 41
  • AngularFire is currently on 0.8.2. There are some bug fixes between 0.8 and the latest. – Kato Sep 25 '14 at 14:18
0

I don't know if I missunderstood, but:

var currentIndexChangeHandler = function(newValue, oldValue) {
    scope.challenges.forEach(function(challenge) {
        //do something
    }
}
scope.$watch('currentIndex', currentIndexChangeHandler);

will provoke that "currentIndexChangeHandler" will be triggered on the very first run (see: $watch is triggered directly after init, why?), when "scope.challenges" is still undefined.

You colud "hack" this "first run" with "if(newValue!=oldValue)", but I think this is not the point. Other problem is that when you iterate "scope.challenges", it is undefined, because its value should be async received. It could be solved using "if(Boolean(scope.challenges))", but it's not the right way.

I think the real problem is that you are working with async data.

¿What value returns Challenge.findAll()? ¿maybe a promise? In this way you should use:

Challenge.findAll().then(function(challenges){
    $scope.challenges = challenges;
}

I refactored your code with my sugestion. Is that behaviour, what you was pretending?

http://jsfiddle.net/rizome/uqtaoLne/

UPDATE:

Using Firebase and $firebase (see: https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebase)

"$firebase" AngularJS wraper has a similar behaviour than coded in the fiddle above, but you should use "$firebase" api to obtain a promises. (this piece of code represents code inside your repo-service, and inside the controller as well)

var firebaseResource = $firebase(new Firebase(YOUR_DATA_URL));
var firebaseSyncArray = firebaseResource.$asArray(); //it is still empty
var loadedArrayPromise = firebaseSyncArray.$loaded(); //promise with the array when loaded
var loadedArrayPromise.then(function (challenges) {
        $scope.challenges = challenges; //now, you can set $scope.challenges
});
Community
  • 1
  • 1
rizome
  • 66
  • 2
  • 5