ndemoreau
ndemoreau

Reputation: 3869

angularjs child controller has no access to parent

I have Two nested controllers:

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})

They are used this way in my nested views:

<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>

When I hit refresh on the browser, it works fine but when I click a building from a building lists page, it fails because $scope.building is undefined in AddressesChildCtrl.

Why doesn't the child controller have access to the parent controller's scope in this case?

The app is visible here: http://lgi.herokuapp.com/buildings/

Thx!

Upvotes: 0

Views: 654

Answers (1)

rtcherry
rtcherry

Reputation: 4880

If you are using ngResource, Building.get will return an empty object immediately and will asynchronously fill in the object data after the HTTP request is complete (documentation). You can do something like this to load the address data when the object is filled in:

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);
}

Upvotes: 2

Related Questions