Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-serviceangularjs-timeout

AngularJS: $timeout within directive's controller using "this"


Not sure if everything is wired up here correctly. The objective is to call the nextSlide function, for it to change the class, wait a second, then incrament the current picture by 1, and then change the class back. I think the problem is the scope, but I don't use $scope anywhere in my code and all examples of this use it. The timeout is completely skipped over when it's run.

How do I get $timeout to execute?

var app = angular.module('cole', []);
app.directive('slideShow',['$timeout', function() {
    return{
        restrict: 'E',
        templateUrl: 'slide-show.html',
        controller: function(){


this.nextSlide = function() {

                document.getElementById("frontPic").className = "fadeOut";

                    this.$timeout(function() {

                    this.setCurrent(this.current + 1);

                    document.getElementById("frontPic").className = "picFront";

                }, 1000);
            };

      },
        controllerAs: 'pics'
    };
}]);

The full code is here https://github.com/Cameron64/Angular


Solution

  • No, $timeout is an argument of the enclosing function, not a member of this. The correct code is:

    app.directive('slideShow',['$timeout', function($timeout) {
        ...
        $timeout(function() {
            ...
    

    Also pay extra attention: as it stands neither setCurrent() is a member of this, i.e. the controller object. It probably needs to be corrected as well.