jQuery如何在自定义指令中响应$scope的变化?

angular - How can jQuery inside a custom directive respond to a $scope change?

本文关键字:scope 变化 响应 自定义 指令 jQuery      更新时间:2023-09-26

jQuery如何在自定义指令中响应$scope的变化?

<div id="wrapper" scrolldirective>          
  <div id="scroller">Hello this is a test<div>
</div>

注意:$timeout只在指令内部,用于将。scrolltop()推到更新周期的末尾,就像这个线程一样。jQuery:水平滚动控制器或指令中的div

myapp.directive('scrolldirective', function($timeout) {
  return {
    restrict: 'A',
      link: function(scope, element, attrs) {
      $timeout(function() {
        $(element).scrollTop( scope.mytop );
      }, 1);
    }
  };
});

最后是一些$scope代码,我想让指令对

做出反应
$scope.mytop = 500;  
$timeout(function(){
  $scope.setPosition(50);
},1000);
$scope.setPosition = function(arg){
  $log.log('===> ',arg);
  $scope.mytop = arg;
  $scope.$apply();  // ???
}
编辑:

这里是一个jsFiddle,其中包含了运行该程序所需的所有最小代码。不幸的是,jsFiddle的UI将自己的滚动条添加到面板中,这会干扰到这一点!嗯……。但至少所有的代码都在那里,如果你想复制的话。http://jsfiddle.net/PrimeLens/CV5L8/

我没有收到Ian的回复(见评论),但他的话让我找到了解决方案。我在这里发布了一组工作代码https://github.com/PrimeLens/angular-MVP-custom-directive-jquery-with-data-binding

scope.$watch('variableName', function() {
    // 
});