0

我有两个嵌套控制器:

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/

谢谢!

4

1 回答 1

2

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

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);
}
于 2013-06-06T10:28:43.133 回答