无法使用ngShow为自定义指令制作动画

Cannot Animate Custom Directive with ngShow

本文关键字:指令 动画 自定义 ngShow      更新时间:2023-09-26

我正在尝试使用ng-show来动画化一个自定义模态指令,遵循Angular网站上显示的示例(示例位于页面的最底部)。然而,我没有任何运气让它发挥作用。

我使用Angular 1.3.x和Bootstrap 3.3.x。我不使用Angular UI Bootstrap,因为自定义模式指令更适合我的需求。

到目前为止,我得到的是:

Modal.js:

angular.module('plunker', [])
  .directive('myModal', function() {
    return {
      restrict: 'E',
      transclude: true,
      replace: true,
      templateUrl: 'modal.html',
      controller: 'ModalCtrl',
      link: function(scope, element, attrs) {
        scope.showModal = false;
        if (attrs.title === undefined) {
          scope.title = 'Modal Title Placeholder';
        } else {
          scope.title = attrs.title;
        }
        scope.$watch('showModal', function(isHidden) {
          if (isHidden) {
          } else {
          }
        });
      }
    };
  }).controller('ModalCtrl', ['$scope',
    function($scope) {
      $scope.$open = function() {
        $scope.showModal = true;
      };
      $scope.$close = function() {
        $scope.showModal = false;
      };
    }
  ]);

modal.html:

<div role="dialog" tabindex="-1" class="modal modal-fade" ng-show="showModal">
    <div class="modal-backdrop" style="height: 100%"> </div>
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">{{title}}</h3>
            </div>
            <div class="modal-body">
                <div class="content" ng-transclude></div>
            </div>
        </div>
    </div>
</div>

modal.css:

.modal-fade {
  opacity: 1;
  display: block !important;
}
.modal-fade .ng-hide-add .ng-hide-add-active,
.modal-fade .ng-hide-remove .ng-hide-remove-active {
  -webkit-transition: all linear 1s;
  -moz-transition: all linear 1s;
  transition: all linear 1s;
}
.modal-fade .ng-hide {
  opacity: 0;
  display: none;
}

index.html:

<my-modal title="Example Modal">
    <p>Some text</p>
    <button type="button" class="btn btn-primary" ng-click="$close()">Close</button>
</my-modal>
<button type="button" class="btn btn-primary" ng-click="$open()">Open Modal</button>

其他一切都很好,即模态显示并可以关闭,但没有动画。

这里有一个指向代码的Plunkr链接

AngularJS的动画挂钩在一个名为ngAnimate的单独模块中实现。

加载脚本:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular-animate.min.js"></script>

并添加模块:

angular.module('plunker', ['ngAnimate'])

其次,您需要连接CSS类以形成正确的选择器。

代替:

.modal-fade .ng-hide {

Do:

.modal-fade.ng-hide {

第一个是decedent选择器,它将选择具有类ng-hide并且是具有类modal-fade的元素的后代的元素。

第二个将选择同时具有这两个类的元素,这正是您所需要的。

对于这种情况,您只需要:

.modal-fade {
  -webkit-transition: all linear 1s;
  -moz-transition: all linear 1s;
  transition: all linear 1s;
  display: block;
}
.modal-fade.ng-hide {
  opacity: 0;
}

display: block只需要覆盖Bootstrap中modal类中的display: none

演示:http://plnkr.co/edit/h0tNOn6Xj31OGmHqulr5?p=preview