angularjs子控制器 - 访问变量

时间:2014-03-20 18:18:01

标签: angularjs

假设我有以下内容:

<div ng-controller="PeopleCtrl">
    <div ng-repeat="person in people" ng-controller="PersonCtrl">
        <p>{{person.name}}</p>
        <div>[LOTS OF COMPLICATED DATA RELATED TO A PERSON THAT I NEED TO ORGANIZE IN A CONTROLLER]</div>
    </div>
</div>

然后我有两个控制器

app.controller('PeopleCtrl', ['$scope', function($scope){ $scope.people = [etc, etc, etc ];}];
app.controller('PersonCtrl', ['$scope', function($scope){ HOW DO I ACCESS THE PERSON OBJECT IN THIS CONTROLLER? }];

在上面的PersonCtrl中,我如何访问&#34; person&#34; ng-repeat中提到的对象?

3 个答案:

答案 0 :(得分:1)

您只需在$scope.person的{​​{1}}下访问即可。嵌套作用域继承自其高级作用域。

请参阅http://plnkr.co/edit/EeFOoUEagmsIHL3XlUBx?p=preview上的示例:

<强> HTML:

PersonCtl

<强> JS:

<div ng-controller="PeopleCtrl">
    <div ng-repeat="person in people" ng-controller="PersonCtrl">
        <p>
          First Name: {{person.firstName}}<br/>
          Last Name: {{person.lastName}}
        </p>

        <div>
          Full Name (from <code>PersonCtrl</code>): {{person.fullName}}
        </div>
        <hr>
</div>

答案 1 :(得分:0)

 app.controller('PersonCtrl', ['$scope', function($scope){
      $scope.name;
 });

答案 2 :(得分:0)

它将以与父控制器相同的名称提供。要查看已继承的变量,只需进入子控制器和console.log($ scope)这是一个对象,在调试器控制台中,您可以展开它,看看是否正确设置了继承。

当控制器使用原型继承相互继承时,如果它们在当前范围内找不到,它们将在名称的链中进一步查找。

这是一个傻瓜:

http://plnkr.co/edit/WwZC8tMW0swjKDAS7n4B

angular.module('app', [])
 .controller('PeopleCtrl', function($scope) {
$scope.people = [{name: 'Bob'}, {name: 'Steve'}, {name: 'Jim'}]
 })

.controller('PersonCtrl', function($scope) {
   console.log($scope.people)
 });

HTML:

  <body ng-app='app'>
    <div ng-controller="PeopleCtrl">
      <div ng-repeat="person in people" ng-controller="PersonCtrl">
          <p>{{person.name}}</p>
          <div>[LOTS OF COMPLICATED DATA RELATED TO A PERSON THAT I NEED TO ORGANIZE IN A CONTROLLER]</div>
      </div>
    </div>
  </body>