注意第二次在指令中更改范围时不要触发

时间:2013-10-04 01:08:50

标签: angularjs angularjs-directive

我在指令中制作精灵,并且正在观察范围变量scope.isAnimating。单击精灵时,将反转该值并停止/启动动画。手表会在第一次单击元素时触发,但值会更改,但不是第二次。

这不是完整的指令,而是缩写版本。如果你想看到这种情况发生live,请点击精灵停止,然后再次点击它以启动(不起作用)。

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;
   });


  }
}
});

如何让手表同时完成两次点击?

1 个答案:

答案 0 :(得分:3)

您需要使用$ scope。$ apply函数修改范围属性。它目前不起作用,因为您在自定义回调之外修改范围。

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

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

相关问题