How to trigger an angularjs animation from a controller method?

后端 未结 3 1230
野的像风
野的像风 2021-01-20 19:42

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 issu

3条回答
  •  后悔当初
    2021-01-20 20:03

    Here is the solution I ended up using (see code below). It is an adaptation of Liamnes's proposed solution.

    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:

提交回复
热议问题