angularjs子控制器无法访问父级

时间:2013-06-06 09:44:40

标签: angularjs

我有两个嵌套控制器:

BuildingsShowCtrl = ($scope, $location, $routeParams, Building) ->
  $scope.building = Building.get
    id: $routeParams.id

AddressesChildCtrl = ($scope, $routeParams, Address) ->
  $scope.addresses = Address.query({building_id: $scope.building.id})

它们在我的嵌套视图中以这种方式使用:

<div ng-controller="BuildingsShowCtrl">
  <h1>Building</h1>

  <p>
    <b>Name</b><br>
    {{building.name}}
  </p>

  <p>
    <b>Number</b><br>
    {{building.number}}
  </p>
  <div ng-include="'/assets/addresses/index.html'"></div>
</div>

当我在浏览器上点击刷新时,它工作正常,但是当我从建筑物列表页面单击某个建筑物时,它会失败,因为$ scope.building在AddressesChildCtrl中未定义。

为什么子控制器在这种情况下不能访问父控制器的范围?

此处可以看到该应用:http://lgi.herokuapp.com/buildings/

THX!

1 个答案:

答案 0 :(得分:2)

如果您使用ngResourceBuilding.get将立即返回一个空对象,并在HTTP请求完成后异步填写对象数据(documentation)。您可以执行以下操作来在填充对象时加载地址数据:

AddressesChildCtrl = function($scope, $routeParams, Address) {
  $scope.$watch('building.id', function(newValue, oldValue) {
    if (newValue) {
      $scope.addresses = Address.query({building_id: $scope.building.id})
    } else {
      $scope.addresses = []
    }
  }, true);
}