用 AngularJS 摇动动画

Shake animation with AngularJS

我还在学习AngularJS并且之前一直在使用jQuery等来记录同样的感觉。

我有一个登录功能,如果成功登录则重定向用户,否则 - 就目前而言 - 打印到控制台。 如果密码不正确我想"shake"表格-html-DOM

这是我控制器中的代码:

    user.login(self.username, self.password).then(
        function(res) {
            $location.path('/dashboard');
        }, function(res) {
            console.log(res.data.error);
        }
    );

使用 jQuery 我会做类似的事情:

    user.login(self.username, self.password).then(
        function(res) {
            $location.path('/dashboard');
        }, function(res) {
            $("#my-login-form").shake();
        }
    );

这当然不适用于AngularJS。做类似事情的最简单和最好的方法是什么?我已经尝试阅读 ngAnimate 文档,但需要更好的 understanding/example 之类的东西。

您可以使用 CSS 添加动画。例如 animate.css 然后使用 angular 在发生某些事情时添加 class。

示例:

查看:

<div ng-class="{'shake':error}" style="width:200px;height:200px;background:blue" class="animated"></div>

控制器:

user.login(self.username, self.password).then(
    function(res) {
        $location.path('/dashboard');
    }, function(res) {
        console.log(res.data.error);
        $scope.error = true;
        setTimeout(function(){ 
            $scope.error = false;
        }, 1000);
    }
);

解释:

ng-class="{'shake':error}"

如果错误变量为真,则有条件地添加"shake" class。与 "animated" 一起触发抖动效果,如 animated.css 中所定义。您当然也可以创建自己的 css 样式。

演示https://jsfiddle.net/mkraLxs3/3/

您将需要使用 ng-animate。 Here you can find a good tutorial to start using it. And here 你可以找一个 CSS3 动画来摇晃。

您将必须:

  • 将 angular-animate.js 和 ngAnimate 添加到您的 angular 模块
  • 为表单分配 CSS class 动画
  • 当登录 returns 时发生错误更改 CSS class 的动画 属性 以便播放动画。

您可以在我发送给您的第一个教程中找到第 1 点和第 3 点的操作方法,并在第二个教程中找到 css 动画。