Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $timeout - TypeError: object is not a function

Tags:

angularjs

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!

like image 677
Levon Tamrazov Avatar asked Mar 08 '14 17:03

Levon Tamrazov


1 Answers

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) {
like image 54
Aco Mitevski Avatar answered Nov 05 '22 08:11

Aco Mitevski