侦听对象时$watch不起作用



我在控制器的作用域中有一个变量,它的值应该在视图上使用的指令中查看,类似于

<grid options="gridOptions" />    // view's markup
# --- controller ---
# not important, just to show that columns loaded lazily    
schemaService.getColumns().then (cols)-> $scope.columns = cols  
$scope.gridOptions = 
  columns: $scope.columns                 # here, this wouldn't work
  # but, if done like this:
  columns: -> return $scope.columns       # note: it's a function 

# --- and inside the 'grid' directive ---
cols = -> 
  return scope.options.columns           # again this wouldn't work
  return scope.options.columns()         # but if it's done like a function - does
scope.$watch cols, (newVal, oldVal)->
    console.log "columns changed"
,true

正如你所看到的,当我把gridOptions.columns的值作为一个函数时,它是有效的,如果我把它作为一个对象,$watch看不到任何变化,

我不想把它作为一个函数,我想把它当作一个对象来访问,我甚至试图让gridOptions.columns返回自可执行的-仍然不起作用

我很好奇为什么会发生这种情况

问题是$scope.gridOptions.columns绑定到基元。为了让它按您的意愿运行,您需要修改控制器,以便通过引用传递列:

$scope.gridOptions = {}
schemaService.getColumns().then (cols) -> 
  $scope.gridOptions.columns = cols

指令中的$watch现在将按预期对更改做出反应。

最新更新