2013-10-04 74 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