Angular:如何强制重新编译指令?

Luc*_*cia 8 javascript angularjs angularjs-directive

HTML:

<div ng-repeat="obj in arr">
   <custom-directive status-stored-in="obj"></custom-directive>
</div>
Run Code Online (Sandbox Code Playgroud)

问题:

我为大量的objs 内置了翻页.这意味着arr代表objs 当前页面的值将发生变化.然而,objstatus-stored-in="obj"部分不与改变刷新.

现在我的解决方案是添加一个ng-ifin customDirective,来回闪烁它的值以强制重新编译.还有其他等效的,更简洁的方法来处理这个问题吗?

编辑:

自定义指令的开头:

module.directive 'checkbox', (checkboxHooks) ->
  restrict: 'E'
  scope:
    hook: '='
    hookedTo: '='
    statusStoredIn: '='
  templateUrl: 'templates/checkbox.html'
  link: (scope, element, attr) ->
Run Code Online (Sandbox Code Playgroud)

要点是它需要抓住一个对象来存储checked状态.整个过程可以在这里找到:[ coffee/js ].

Dan*_*ink 7

在您的指令链接功能中,您需要注意status-stored-in更改,然后重新编译它,例如:

   link: function(scope, element) {
    scope.$watch('statusStoredIn', function() {
      element.html(statusStoredIn);
      $compile(element.contents())(scope);
    });
   }  
Run Code Online (Sandbox Code Playgroud)

  • 这会导致内存泄漏.你需要做var watch = scope.$ watch ...然后调用$ compile做watch(); ,否则每次重新编译后你都会再看一次. (4认同)
  • 是不是`$ compile(element.contents())`用于编译childNodes?但我需要重新编译自己. (2认同)