AngularJS $ Timeout Service

I should have something visible for 3-4 seconds. I am trying to use $ timeout to achieve this. Here is 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 does not work, and I cannot solve the problem. What am I doing wrong? Should I use a timeout in this case.

+4
source share
3 answers

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;
};

In the broadcast mode, make the element visible, start the timeout so that $ scope.close is called after 3 seconds. No need for $ timeout.cancel in your case.

+1
source

What about:

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

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

+2
source

. - , . , , false -. .

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>
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1653791/


All Articles