如何在angularjs中显示特定时间的消息

时间:2014-05-01 17:21:10

标签: angularjs

    <script>
      function Ctrl($scope, $window) {
        $scope.greeting = 'Hello, World!';
        $scope.doGreeting = function() {
           $scope.msg="hi";
        };
      }
    </script>
    <div ng-controller="Ctrl">
      <input type="text" ng-model="greeting" />
      <button ng-click="doGreeting()">click</button>
    {{msg}}
    </div>

嗨,我在这里显示一条消息,当用户点击按钮时。我想显示此消息10秒然后隐藏。请你帮助我如何在angularjs中实现这一点。

3 个答案:

答案 0 :(得分:7)

您可以设置一个变量来确定是否显示消息,并在10,000秒后隐藏它。你必须注入$ timeout,如下所示。然后在您的视图中,您需要在{span}中包含{{msg}}才能使用ng-show

<script>
  function Ctrl($scope, $window, $timeout) {
    $scope.greeting = 'Hello, World!';
    $scope.showGreeting = false;
    $scope.doGreeting = function() {
       $scope.msg="hi";
       $scope.showGreeting = true;
       $timeout(function(){
          $scope.showGreeting = false;
       }, 10000);
    };
  }
</script>
<div ng-controller="Ctrl">
  <input type="text" ng-model="greeting" />
  <button ng-click="doGreeting()">click</button>
  <span ng-show="showGreeting ">{{msg}}</span>
</div>

答案 1 :(得分:1)

我在angularjs中显示特定时间的消息的方法是使用 AngularJS-Toaster

要使用该库,请按以下步骤操作:

<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/0.4.9/toaster.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js" ></script>
<script src="https://code.angularjs.org/1.2.0/angular-animate.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/0.4.9/toaster.min.js"></script>

添加烤箱容器指令:

<toaster-container></toaster-container>

准备烤面包机的方法:

// Display an info toast with no title
    angular.module('main', ['toaster'])
    .controller('myController', function($scope, toaster) {
        $scope.pop = function(){
            toaster.pop('success', "title", "text");
        };
    });

点击按钮时调用控制器方法:

<div ng-controller="myController">
    <button ng-click="pop()">Show a Toaster</button>
</div>

在这里,您可以看到Plunker显示多种显示不同消息的祝酒词

答案 2 :(得分:0)

$timeout依赖项添加到您的控制器。这是一个fiddle

<div ng-app>
    <div ng-controller="Ctrl">
        <input type="text" ng-model="greeting" />
        <button ng-click="doGreeting()">click</button>
        <div class="ng-hide" ng-show="showMessage">{{msg}} {{ greeting }}</div>
    </div>
</div>
function Ctrl($scope, $window, $timeout) {
    var messageTimer = false,
        displayDuration = 5000; // milliseconds (5000 ==> 5 seconds)

    $scope.showMessage = false;
    $scope.msg = "hi";

    $scope.doGreeting = function () {
        if (messageTimer) {
            $timeout.cancel(messageTimer);
        }

        $scope.showMessage = true;

        messageTimer = $timeout(function () {
            $scope.showMessage = false;
        }, displayDuration);
    };
}