AngularJS指令中的动画,事件未触发

时间:2016-04-29 15:44:35

标签: javascript angularjs

我在尝试进入'进入'指令中的事件。加载模板时,事件不会触发。

这是应用声明

angular
  .module('MyApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl'
      })
      .when('/in-the-community', {
        templateUrl: 'views/in-the-community.html',
        controller: 'CommunityCtrl'
      })
       .otherwise({
        redirectTo: '/'
      });
  });

最初我使用路由提供程序给我一个模板页面。然后我尝试在这些模板中使用指令来提供另一个视图。这可以通过在我的模板页面中使用以下内容来实现

<div class="flex">
    <div class="fc fci image-wrapper" id="home-banner">
    </div>

    <div class="fc fcc">
        <section show-and-hide-content="{{ sub_content }}">
        </section>
    </div>
</div>

这将加载以下指令

angular.module('rubisApp')
  .directive('showAndHideContent', function ($animate) {
    return {
      templateUrl: 'views/community-sub.html',
      controller: 'CommunitySubCtrl',
      link: function(scope, element, attributes) {
        $animate.on('enter', element,
           function callback(element, phase) {
             console.log('attributes.showAndHideContent');
           }
        );
       }
     };
   });

控制台日志没有运行,我只能假设这是因为它没有触发$animate.on事件。

angular会将ng-enter类应用于指令中的templateUrl吗?

我对角度很陌生,所以如果这是错误的做法,那么替代方案也会有所帮助。

2 个答案:

答案 0 :(得分:3)

没有被引入指令的$ animate依赖。

angular.module('MyApp')
  .directive('showAndHideContent',['$animate', function ($animate) {
    return {
      templateUrl: 'views/community-sub.html',
      controller: 'CommunitySubCtrl',
      link: function(scope, element, attributes) {
        $animate.on('enter', element,
           function callback(element, phase) {
             console.log('attributes.showAndHideContent');
           }

        );

      }

     };
   }]);

答案 1 :(得分:0)

我看到你正在使用控制器。你不能在那里创造活动吗? 我检查了我的代码,并在控制器上有这个片段,在路由更改时销毁间隔,注意我使用$ on和'$ destroy',带$。可以吗?

$scope.$on('$destroy', function () {
                    $interval.cancel($scope.interval);
                });