0

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!

2
  • Can you create a plunker snippet to check? From source you've posted in question there I can't see where do you use AddressesChildCtrl Commented Jun 6, 2013 at 10:05
  • I think you need to use $scope.$parent.building - can you try with this and check? Commented Jun 6, 2013 at 10:11

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Excellent, It works! You made my day! Is the $watch needed because otherwise, the query is executed on Address BEFORE a response has been received from Buildings? Thx!
The watch is just detecting a change in the building id. So undefined => 1, or 1 => 2. If you wanted to wait for the building to load, you would need to use promises, which are not available on the stock ngResource in the 1.0.x builds of AngularJS. You could also pass a callback to Building.get, but the way your controllers are split up that could be odd.
Last question: does that mean that if I used $routeParams.id, which is the same as the building_id, It would load faster?
That would allow you to query the address immediately after the route change, even if the building is still loading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.