4

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.

3 Answers 3

2

what about:

$scope.$on(broadcastService.topErrorBar.show,
      function(event, message) {
          $scope.isVisible=false; 
           $timeout(function () { $scope.isVisible= true; }, 3000); 
      });

you have to use in html ng-show="isVisible">

Sign up to request clarification or add additional context in comments.

1 Comment

Best solution imo.
1

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

1

Your logic is inverted. The function in a timeout fires after the time has elapsed. You want the element to be visible, and then set visibility to false in your timeout function. Here's an example.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
    $scope.visible = true;
    $timeout(function () {
      $scope.visible = false;
      }, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  This is always visible.
  <span ng-show="visible">This should hide after 3 seconds</span>
</div>

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.