philosophocat
philosophocat

Reputation: 119

angularjs: $timeout usage (inside of service)

I'm trying to make a little notifier, that informs about typical situations: need authorization, changes saved etc. Notices are shown for 3 seconds and disappear, if user didn't click on it (if notice clicked, it disappears immediatly). Documentation is not very informative. How should i use $timeout, to call close(); after 3 seconds? And how can i put a variable (nId) into function? I tried with closure (*function(){return function(){}}*) in default setTimeOut(), but unsuccessfully.

myApp.controller('noticesCtrl',
    function noticesCtrl($scope, $rootScope, noticesData){
        $rootScope.notices = [];
        $scope.closeNotice = function(nId){
            noticesData.close(nId);
        };
    });

myApp.factory('noticesData', function($rootScope, $timeout){
    return{
        add: function(type, text){
            var nId = $rootScope.notices.length + 1;
            $rootScope.notices.push({id: nId, type:type, text:text+nId});
            // call close function with 3sec. delay; how?
        },
        close: function(nId){
            angular.forEach($rootScope.notices, function(notice, key){
                if(notice.id == nId){
                    $rootScope.notices.splice(key,1);
                }
            });
        }
    }
});

Upvotes: 8

Views: 23006

Answers (2)

Yasser Shaikh
Yasser Shaikh

Reputation: 47784

Heres how to do it

$timeout(function () {

    // do something

}, 50);

Upvotes: -2

AlwaysALearner
AlwaysALearner

Reputation: 43947

myApp.factory('noticesData', function($rootScope, $timeout){
    var obj = {};
    obj.add = function(type, text){
        var nId = $rootScope.notices.length + 1;
        $rootScope.notices.push({id: nId, type:type, text:text+nId});
        $timeout(function(){
            obj.close(nId);
        },3000);
    }
    obj.close = function(nId){
        angular.forEach($rootScope.notices, function(notice, key){
            if(notice.id == nId){
                $rootScope.notices.splice(key,1);
            }
        });
    }
    return obj; 
});

Upvotes: 4

Related Questions