angularjs孩子控制器父进不去 [英] angularjs child controller has no access to parent

查看:156
本文介绍了angularjs孩子控制器父进不去的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个嵌套的控制器:

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>

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

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?

该应用程序是可见这里: http://lgi.herokuapp.com/buildings/

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

THX!

推荐答案

如果您使用的是 ngResource Building.get 将立即返回一个空的对象和对象数据将异步填补了HTTP请求完成后(的文档)。你可以做这样的事情来加载地址数据对象时填写的:

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

这篇关于angularjs孩子控制器父进不去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆