【问题标题】:Conditionally calling a directive有条件地调用指令
【发布时间】:2015-07-11 15:34:00
【问题描述】:

让我先说我是 Angular 的新手。我现在正在使用 Angular 进行我的第一个项目,并且遇到了一个多天的问题。我正在开发的功能可以用 jQuery 完成,但我想了解 Angular 的方式。

我想让一组元素在页面上弹跳(就像一个旧的屏幕保护程序,我知道这很愚蠢)。我有一个指令可以很好地处理这个问题。

cancerApp.directive('ngSlider', function() {
  return {
    scope: true,
    template: "<li class='ng-slider' ng-style='pos'>{{choice}}</li>",
    replace: true,
    controller: function($scope, $interval, $element) {
      $scope.pos = {
        top: 0,
        left: 0.
      };

      $scope.newPos = function() {
      $scope.h = window.innerHeight - 50;
      $scope.w = window.innerWidth - 50;
      $scope.pos.top = (Math.random() * $scope.h) + "px";
      $scope.pos.left = (Math.random() * $scope.w) + "px";
      }

    $interval($scope.newPos, 1000);

    }
  }
});

我这样调用指令:

<li ng-slider class="choices" ng-click="selected(choice)" ng-repeat="choice in momChoice">
    {{choice}}
</li>

我的问题是,当用户将鼠标悬停在元素上时,我希望元素停止移动。然后(如果可能)在用户将鼠标悬停在元素之外时再次开始移动。

我已经寻找在线帮助并进行了几次尝试。我尝试在指令中、控制器上以及在 ng-mouseenter 和 ng-mouseleave 中调用的函数中添加条件语句,结果不一。

我觉得我一直在思考 jQuery。我想更好地了解 Angular 如何处理这些情况。非常感谢任何可以为我指明正确方向的想法、解决方案或资源。

【问题讨论】:

    标签: javascript angularjs events angularjs-directive dom-manipulation


    【解决方案1】:

    您的确切可能如下所示。正如@tpie 所说,它的扩展答案

    指令

    cancerApp.directive('ngSlider', function() {
      return {
        scope: true,
        template: "<li class='ng-slider' ng-style='pos'>{{choice}}</li>",
        replace: true,
        controller: function($scope, $interval, $element) {
          $scope.pos = {
            top: 0,
            left: 0.
          };
    
          $scope.newPos = function() {
          $scope.h = window.innerHeight - 50;
          $scope.w = window.innerWidth - 50;
          $scope.pos.top = (Math.random() * $scope.h) + "px";
          $scope.pos.left = (Math.random() * $scope.w) + "px";
          }
    
          var interval = $interval($scope.newPos, 1000); 
          element.on('mouseenter', function(){
              if(interval)
                $interval.cancel(interval);
          })
          element.on('mouseleave', function(){
              interval = $interval($scope.newPos, 1000);
          })
    
        }
      }
    });
    

    【讨论】:

    • 哇,我如此接近了很多次。谢谢您的帮助!我认为我不能调用像 cancel() 函数这样简单的东西,所以我试图切换类并删除 attr(s)。再次感谢。
    • @figbomb 不要忘记接受答案..你可以接受 tpie/me 的答案
    • 接受你的答案 b/c 关键部分是if(interval) $interval.cancel(interval); })
    【解决方案2】:

    将指令动画代码包装成这样的代码

       $element.on('mouseenter', function() {
           //clearInterval here - stop the animation
       });
       $element.on('mouseleave', function() {
           //start the animation
       });
    

    【讨论】:

    • 感谢您的帮助!我做了那件事,但我不明白如何停止动画。我被困在试图切换类,一起删除 attr,然后将其重新添加到另一个 mouseenter 上。显然我把它弄得太复杂了。
    猜你喜欢
    • 2017-11-19
    • 2019-03-27
    • 1970-01-01
    • 2011-12-15
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多