Stefan Stefan - 2 months ago 20
AngularJS Question

AngularJS $timeout service

I have to have something visible for 3-4 seconds. I am trying to use $timeout for achieving that. Here's what I got so far:

$timeout(function() {
debugger;
$scope.$on(broadcastService.topErrorBar.show,
function(event, message) {
$scope.rootElement.addClass('is-visible');
$scope.isVisible = true;
$scope.message = message;
});
}, 3000);

$timeout.cancel(function() {
$scope.close();
});

$scope.close = function() {
$scope.rootElement.removeClass('is-visible');
$scope.isVisible = false;
};


This is not working and I'm not able to resolve the issue. What am I doing wrong? Should I use a timeout in this case.

Answer

It should be like this :

$scope.$on(broadcastService.topErrorBar.show,
  function(event, message) {
    $scope.rootElement.addClass('is-visible');
    $scope.isVisible = true;
    $scope.message = message;
    $timeout(function() {
    $scope.close();
}, 3000);

$scope.close = function() {
  $scope.rootElement.removeClass('is-visible');
  $scope.isVisible = false;
};

On Broadcast , make element visible , start a timeout so that after 3 seconds $scope.close will be called. No need for $timeout.cancel in your case.

Comments