2015-06-14 72 views
1

我在td标记(它位于tr标记内)中有一个div。这div有需要$watch元素的scrollHeight自定义指令:

<tr ng-show="showRow"> 
    <td> 
     <div my-custom-directive>My very long text</div> 
    </td> 
</tr> 

和指令:

appDrct.directive('myCustomDirective', [function() { 

    return { 
     restrict : 'A', 
     compile : function(elem, attr, linker) { 


      return function(scope, element, attributes) { 
      scope.$watch(element[0].scrollHeight, function(){ 
       console.log('triggered'); 
      }) 
      } 
     } 
    } 
}]) 

showRow通过ng-click变量的变化。

的问题是,$watch永远不会触发(除第一次),即使由于ng-showscrollHeight变化(scrollHeight等于0时ng-show等于false)。

我开始还以为是因为我不得不使用$scope.$apply,但我不知道在哪里把它...

+0

没关系... angularJS允许两个! – ncohen

+0

没有。它不会允许 – simon

+0

无论如何它不能解决我的问题... – ncohen

回答

4

你不能看直接的对象引用(这就是你要做的)。您可以观察当前范围的属性(通过以字符串形式提供属性的名称),或者观察函数,该函数返回新值。

更改您的手表:

scope.$watch(function(){ return element[0].scrollHeight }, function(){ 
    console.log('triggered'); 
}); 

在另一方面,作为评论者指出,应使用破折号引用您的指令,而不是骆驼情况下,在DOM。

-1

变化myCustomeDirective我-custome-指令在HTML

<tr ng-show="showRow"> 
    <td> 
     <div my-custome-directive>My very long text</div> 
    </td> 
</tr> 

指令

appDrct.directive('myCustomDirective', [function() { 

    return { 
     restrict : 'A', 
     compile : function(elem, attr, linker) { 


      return function(scope, element, attributes) { 
      scope.$watch(function(){ return element[0].scrollHeight }, 
       function(){ 
         console.log('triggered'); 
       }) 
      } 
     } 
    } 
}]) 
+0

它不回答这个问题,请删除它! – ncohen

+0

我正要回答。这里网速很慢。 – simon

+0

你刚刚从@Thor复制了答案 – ncohen