如何淡出和删除由ng-repeat创建的元素

时间:2013-08-31 11:02:34

标签: javascript jquery angularjs

我有使用以下内容创建的消息列表:

var messages = ["Foo Bar", "Lorem Ipsum", "Dolor Sit Amet"];
app.controller('fooControler', function($scope) {
    $scope.messages = [
        {"message": "Hello There"}
    ];
    function insert() {
        var random = Math.round(Math.random()*(messages.length-1));
        var message = messages[random];
        messages.splice(random, 1);
        $scope.$apply(function() {
            $scope.messages.push({message: message});
        });
        if (messages.length) {
            setTimeout(insert, 5000);
        }
    }
    setTimeout(insert, 5000);
});

我的ng-html看起来像这样:

<html ng-app="app">

<body ng-controller="fooControler">
    <header>
        <div>You have {{messages.length}} messages</div>
        <ul ng-repeat="message in messages">
            <li>{{message.message}}</li>
        </ul>
    </header>
</body>
</html>

如何FadeOut消息并删除它们?我知道如何在jQuery中这样做,但我怎么能用AngularJS方式呢?

JSFiddle

1 个答案:

答案 0 :(得分:3)

从AngularJS 1.1.4开始,添加ngAnimate指令以支持动画。

你可以这样做:

<ul ng-repeat="message in messages" ng-animate="'animate'">
    <li>{{message.message}}</li>
</ul>

这就是所需的css:

.animate-enter-setup, .animate-leave-setup {
    -webkit-transition: 1s linear all;
    /* Safari/Chrome */
    -moz-transition: 1s linear all;
    /* Firefox */
    -ms-transition: 1s linear all;
    /* IE10 */
    -o-transition: 1s linear all;
    /* Opera */
    transition: 1s linear all;
    /* Future Browsers */
}
.animate-enter-setup {
    opacity: 0;
}
.animate-enter-setup.animate-enter-start {
    /* The animation code itself */
    opacity: 1;
}
.animate-leave-setup {
    opacity: 1;
}
.animate-leave-setup.animate-leave-start {
    /* The animation code itself */
    opacity: 0;
}

Working Demo