Back

angular的controller与directive的执行顺序 ( execution sequence of angular's controller and directive)

发布时间: 2013-08-06 01:39:00

refer to: http://stackoverflow.com/a/18070462/445908

directive 在前
controller 在后。 (在controller 中有ajax请求的时候)

所以,如果需要在directive中使用 controller中的ajax返回结果的变量,需要
setTimeout函数。

# in controller
$http.get('/preview').then( (response) ->
  $scope.tabs = response.data.tabs
  $scope.master_switch = '1'
  console.info 'after get response in controller'
)

# in directive
directive('masterSwitch', ->
  (scope, element, attrs) ->
    alert 'in directive!'   # will show before "after get response in controller"
    console.info scope.master_switch  # is undefined
    setTimeout( -> console.info(scope.master_switch), 50) # => 1

Back