2

我正在为指令中的精灵设置动画,并且有一个scope.isAnimating正在监视的范围变量。单击精灵时,值会反转并且动画停止/开始。第一次单击元素并更改值但不会第二次更改值时,手表会触发。

这不是完整的指令,而是一个缩写版本。如果您想实时看到这种情况发生,请单击精灵停止,然后再次单击它开始(不起作用)。

app.directive('sticker', function(timeFunctions){
return {
  restrict: 'AE',
  replace: true,

scope: {
  isAnimated: '=isanimated',
  Animation: '=animation',
  speed: '=speed'
},

 template: '<div></div>',
 link: function(scope, element, attrs) {

  scope.$watch('isAnimated', function(isAnimated) {
     // fires on the first click but not the second, breakpoint not hit
      if (scope.isAnimated) {
          startAnimation();
      } else {
         timeFunctions.$clearInterval( scope.animateTimeout );
      }
  });

   element.bind('click', function(e) {
      e.preventDefault();
      scope.isAnimated = !scope.isAnimated;
   });


  }
}
});

如何让手表在两次点击时都能正常工作?

4

1 回答 1

3

您需要使用 $scope.$apply 函数对范围属性的修改进行包装。它目前不起作用,因为您在 angular 之外从自定义回调修改范围。

element.bind('click', function(e) {
    e.preventDefault();
    $scope.$apply(function () {
      scope.isAnimated = !scope.isAnimated;
    });
});

但是,我建议您使用 ng-click 指令而不是手动绑定到事件。在这种情况下,您不需要使用 $scope.$apply 包装您的代码。Angular 会在 ng-click 中为你做这件事。

于 2013-10-04T02:59:37.100 回答