2013-10-04 72 views
2

中更改我正在动画一个伪指令中的精灵,并且正在监视范围变量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; 
    }); 


    } 
} 
}); 

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

回答

3

您需要使用$ scope修改范围属性$ apply function。它目前没有工作,因为您修改范围从角度外的自定义回调。

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

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

+0

我的一个不错的菜鸟错误。谢谢。 – lucuma