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);
}
});
}
}
});
This '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.
The $timeout service can be used to call another JavaScript function after a given time delay. The $timeout service only schedules a single call to the function. For repeated calling of a function, see $interval later in this text.
Angular $timeout is a wrapper written for window. setTimeout in form of a try catch block which throws exceptions via $exceptionHandler service. $timeout accepts the function to be delayed, delay time, a boolean to invoke $. apply and parameters to be passed to the function.
In angularjs $timeout service is same as window. setTimeout function in javascript. By using $timeout service in angularjs we can set some time delay to execute our functions or methods based on our requirement.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With