8

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);
                }
            });
        }
    }
});
1
  • Have you checked Toastr JS library? It has several options and it shows quite nice notifications. I just wrapped that in a service in order to use it in AngularJS. (And no, I'm not involved with the team :) ) Commented Nov 30, 2013 at 19:02

2 Answers 2

4
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; 
});
Sign up to request clarification or add additional context in comments.

2 Comments

I dont think I get what you are trying to say but the object must be instantiated before you can use any of its contained methods.
I only say, that call this.close() works well and i thought, that there exists a way to call this.close() with $timeout delay (it doesn't works, but doesn't reports about error too). Anyway, thank you very much.
-2

Heres how to do it

$timeout(function () {

    // do something

}, 50);

Comments

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.