8

我正在将 Angular 与UI Bootstrap一起使用。我创建了将广播警报推送到绑定到视图的警报数组中的自定义指令(呈现为引导警报)。在特定超时后,警报将从阵列中删除(因此从视图中删除)。这是代码:

angular.module('myApp')
  .directive('alerts', function ($timeout) {
    return {
      restrict: 'E',
      templateUrl: 'views/alerts.html',
      scope: true, /*share scope between alerts directives*/
      link: function (scope) {
        scope.alerts = [];

        scope.$on('alert', function (event, alert) {
          var newLength = scope.alerts.push({type: alert.type, msg: alert.message});

          $timeout(function() {
            scope.alerts.splice((newLength-1), 1);
          }, 3000);
        });
      }
    };
  });

我想知道是否可以在删除警报之前向警报添加淡出(或任何其他动画)?任何帮助和提示将不胜感激!

4

2 回答 2

10

In Angular > 1.1.5

You can use angular's built-in animation feature. You basically just add a data-ng-animate="'<animation class>'" on the repeated element.

See this excelent post animation-in-angularjs or the answer from @Nikos.

In Angular 1.0.7 (stable)

is a as far as I know no animation support. However you could build the animation yourself. I'm no angular pro, so this might not be the best approach.

Create a second $timeout that adds a 'fade out CSS3' animation that kicks in before the first timeout triggers:

  1. Create CSS3 animation classes for hiding an alert (there might be already from bootstrap)

    @keyframes fadeOut
    {
      from { opacity: 1.0; }
      to { opacity: 0.0; }
    }
    
    @-webkit-keyframes fadeOut 
    {
      from { opacity: 1.0 }
      to { opacity: 0.0 }
    }
    
    .fade-out
    { 
      animation: fadeOut 2s infinite;
      -webkit-animation: fadeOut 2s infinite;
    }
    
  2. Add a 2nd $timeout:

    $timeout(function() { alert.expired = true; }, 2000);
    
  3. In your template add a conditional class with ng-class:

    <div ng-repeat="alert in alerts" ng-class="{'fade-out': alert.expired}">...</div>
    
于 2013-09-17T09:45:55.697 回答
2

我们有类似的设置;模板:

<div ng-controller="messages">
    <div ng-repeat="msg in messages"
        ng-animate="{enter: 'enter-slide', leave: 'leave-slide'}"
        alert type="msg.type" close="closeMsg($index)">{{msg.msg}}</div>
</div>

控制器很简单,包含以下函数和消息数组:

function closeMsg(index) {
    $scope.messages[index].remove();
}

动画定义(参见ng-animate - 我们使用的是 jQuery UI):

module.animation("enter-slide", function () {
    return {
        setup: function (element) {
            element.hide();
        },
        start: function (element, done, memo) {
            try{
                element.slideDown(function () {
                    done();
                });
            }
            catch(ex){}
        }
    };
});

module.animation("leave-slide", function () {
    return {
        start: function (element, done, memo) {
            element.slideUp(function () {
                done();
            });
        }
    };
});

当然,您可以替换slideUp/Down()为所需的效果。

于 2013-09-17T09:26:01.533 回答