3

I would like to trigger an angular animation from a controller method.

I have come up with something that I am not satisfied with (see code below).

The issue is that for my animation to work, I need to track the state of a $scope variable i.e. $scope.shake:

$scope.signin = function (formCtrl) {
    $scope.shake = false;
    if ($scope.credentials) {
        signinService.signin($scope.credentials, function (status, memberRole) {
                $scope.shake = false;
                //TODO: necessary to check status?
                if (status === 200) {
                    var memberType;
                    if (memberRole === 'ROLE_BASIC_PARENTS') {
                        memberType = 'parents';
                    }
                    if (memberRole === 'ROLE_BASIC_CHILDCARE_WORKER') {
                        memberType = 'childcare-worker';
                    }
                    $rootScope.globals = {
                        memberType: memberType,
                        authenticated: 'OK'
                    }

                    $cookies.globalsMemberType = $rootScope.globals.memberType;
                    $cookies.globalsAuthenticated = $rootScope.globals.authenticated;

                    $state.go('dashboard', {memberType: memberType});
                }
            },
            function () {
                $scope.shake = true;
            });
    }
    else {
        $scope.shake = true;
    }
};

<form ng-class="{shake: shake}" name="formCtrl" ng-submit="signin(formCtrl)" novalidate>

Can someone please advise a cleaner solution?

edit 1:

Here is the css code as requested:

@-webkit-keyframes shake {
    0% {
        -webkit-transform: translateX(0);
        transform: translateX(0);
    }

    12.5% {
        -webkit-transform: translateX(-6px) rotateY(-5deg);
        transform: translateX(-6px) rotateY(-5deg);
    }

    37.5% {
        -webkit-transform: translateX(5px) rotateY(4deg);
        transform: translateX(5px) rotateY(4deg);
    }

    62.5% {
        -webkit-transform: translateX(-3px) rotateY(-2deg);
        transform: translateX(-3px) rotateY(-2deg);
    }

    87.5% {
        -webkit-transform: translateX(2px) rotateY(1deg);
        transform: translateX(2px) rotateY(1deg);
    }

    100% {
        -webkit-transform: translateX(0);
        transform: translateX(0);
    }
}

@keyframes shake {
    0% {
        -webkit-transform: translateX(0);
        transform: translateX(0);
    }

    12.5% {
        -webkit-transform: translateX(-6px) rotateY(-5deg);
        transform: translateX(-6px) rotateY(-5deg);
    }

    37.5% {
        -webkit-transform: translateX(5px) rotateY(4deg);
        transform: translateX(5px) rotateY(4deg);
    }

    62.5% {
        -webkit-transform: translateX(-3px) rotateY(-2deg);
        transform: translateX(-3px) rotateY(-2deg);
    }

    87.5% {
        -webkit-transform: translateX(2px) rotateY(1deg);
        transform: translateX(2px) rotateY(1deg);
    }

    100% {
        -webkit-transform: translateX(0);
        transform: translateX(0);
    }
}

.shake {
    -webkit-animation: shake 400ms ease-in-out;
    animation: shake 400ms ease-in-out;
}
4

3 に答える 3

4

フォームをディレクティブでラップし、イベントを介してアニメーションをトリガーすることをお勧めします。たとえば、コントローラーでは次のようにします。

$scope.$broadcast('FORM_ERROR');

そしてディレクティブで、もっと似たようなことをします

scope.$on('FORM_ERROR', function() { // code to trigger animation goes here });

これをイベントとして処理するのは理にかなっています。これは厳密なライフサイクルがあるためです。イベントがディスパッチされ、イベントが処理されます。スコープ変数は、意味がなくなったとしても、ぶらぶらしていました。アニメーションを再びトリガーできるように、元の状態に「リセット」するためのコードが必要な場合もありますが、これにより不要な複雑さが追加されます。

于 2015-05-10T17:51:16.443 に答える
1

最初の失敗後にアニメーションがリセットされないという別の問題が発生するため、連続して失敗するとアニメーションが再度実行されません。残念ながら、純粋な CSS を使用してこれを行う方法はありません。

最初に行うべきことは、Angular が提供する検証サービスを使用してから、エラー アニメーションのロジックを分離することです。

Prefix util factory が正常に機能している実用的なソリューションを次に示します。

  • 最初に関数form.$invalid内をチェックしsignin(formCtrl)、フォームが $invalid であるか、サービスからの応答がログイン エラーを返すかどうかを確認してから、アニメーションを処理する関数を呼び出します。

  $scope.signin = function(form){
    if(form.$invalid){
      $scope.animateError();
    }
  };

  • CSS を変更して、アニメーションのタイミング関数と期間のみを追加します。したがって、showAnimationError関数が呼び出されると、フォーム要素を取り、スタイルanimationName/webkitAnimationNameを値とともに追加しますshake

また、アニメーション終了のイベント リスナーを追加することを忘れないでください。これにより、このスタイルをクリーンアップして、showAnimationError

/* css */
.shake {
    -webkit-animation-duration: 400ms;
    -webkit-animation-timing-function: ease-in-out;
    animation-duration: 400ms;
    animation-timing-function: ease-in-out;
}

$scope.animateError = function(){
  if(!resetAnimationHandler){
    addResetAnimationHandler();
  }
  myForm.style[prefixUtil.animationName] = 'shake';
};

これがお役に立てば幸いです

于 2015-05-11T02:51:45.297 に答える
0

これが私が最終的に使用したソリューションです(以下のコードを参照)。これは、Liamnes の提案されたソリューションの適応です。

angular.module('signin')
    .controller('SigninCtrl', ['$scope', '$rootScope', '$cookies', '$state', '$animate', 'signinService', function ($scope, $rootScope, $cookies, $state, $animate, signinService) {

        var setPersonalInfo = function (param) {
            return signinService.setPersonalInfo(param.headers, $rootScope);
        };
        var goToDashboard = function (memberType) {
            $state.go('dashboard', {memberType: memberType});
        };
        var reportProblem = function () {
            $scope.formCtrl.username.$setValidity('username.wrong', false);
            $scope.formCtrl.password.$setValidity('password.wrong', false);
            $scope.$broadcast('SIGNIN_ERROR');
        };
        var resetForm = function(formCtrl){
            formCtrl.username.$setValidity('username.wrong', true);
            formCtrl.password.$setValidity('password.wrong', true);
        };

        $scope.signin = function (formCtrl) {

            resetForm(formCtrl);

            if (formCtrl.$valid) {
                signinService.signin($scope.credentials).then(setPersonalInfo).then(goToDashboard).catch(reportProblem);
            }
            else {
                $scope.$broadcast('SIGNIN_ERROR');
            }
        }
    }])
    .directive('shakeThat', ['$animate', function ($animate) {
        return {
            require: '^form',
            scope: {
                signin: '&'
            },
            link: function (scope, element, attrs, form) {
                scope.$on('SIGNIN_ERROR', function () {
                    $animate.addClass(element, 'shake').then(function () {
                        $animate.removeClass(element, 'shake');
                    });
                });
            }
        };
    }]);

HTML:

<form shake-that name="formCtrl" ng-submit="signin(formCtrl)" novalidate>
于 2015-05-11T17:24:20.523 に答える