5

I wrote a directive and a service. The directive calls a timeout function in the service. However, once the $timeout is reached, it throws an error:

TypeError: object is not a function

Original $scope.msg is not displayed. And the $timeout function does not wait for (20sec) to call the callback (or so I assume, since the $scope.msg changes right away).

I am absolutely lost. I found a few questions regarding timeouts, but none of them seem to have this problem. This one is as close as I got, and I am already following that answer Angularjs directive TypeError: object is not a function.

Here is a Plunker to the code: http://plnkr.co/edit/xrepQOWIHlccbW5atW88?p=preview

And here is the actual code.

angular.module('myApp', [
    'ui.bootstrap',
    'myApp.services',
    'myApp.directives',
]);

angular.module('myApp.directives', []).
directive('logoutNotification', [
    function(admin) {
        return {
            restrict: "E",
            template: "<div>{{msg}}</div>",
            controller: ["$scope", "$timeout", "admin",
                function($scope, $timeout, admin) {
                    $scope.msg = "Hey, no timeout yet";
                    $scope.resetNotification = function() {
                        admin.resetNoticeTimer(function(){
                          $scope.msg = "Hey, I'm back from timeout"
                        });
                    };
                }
            ],
            link: function(scope) {
                scope.resetNotification();
            }
        };
    }
]);

angular.module('myApp.services', []).
factory('admin', ['$rootScope', '$location', '$timeout',
    function($rootScope, $timeout, $location, admin) {
        var noticeTimer;
        return {
            resetNoticeTimer: function(cb) {
                if (noticeTimer) {
                    $timeout.cancel(noticeTimer);
                }
                noticeTimer = $timeout(cb(), 20000);
            }
        };
    }
]);

Thanks in advance!

1 Answer 1

14

You have misordered the dependencies.

Your code:

factory('admin', ['$rootScope', '$location', '$timeout',
    function($rootScope, $timeout, $location, admin) {

Should be:

factory('admin', ['$rootScope', '$timeout', '$location',
    function($rootScope, $timeout, $location) {
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, thank you, thank you. I've spent 10+ hours on this now. Can't believe I missed that.

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.