ng-controller with ng-repeat,魔术在哪里?

时间:2014-06-27 15:36:10

标签: angularjs scope ng-repeat

main.html中

<div ng-controller="MainCtrl">
  <table ng-controller="RecordCtrl" ng-repeat="record in records">
      <tr>
          <th>Name</th>
          <td>{{ record.name }}</td>
      </tr>
      <tr>
          <th>Team</th>
          <td>{{ record.team }}</td>
      </tr>
  </table>
</div>

app.js

var myApp = angular.module('myApp', []);

function MainCtrl($scope) {
    $scope.records = [
        { name: 'Alessandro Del Piero', team: 'Italy' },
        { name: 'Rui Costa', team: 'Portugal' },
    ];
}

function RecordCtrl($scope) {
    // I don't see here the "record" property
   console.log($scope);

   // I thought this would show undefined
   // ($scope.$parent.record exists, but not $scope.record)
   console.log($scope.record);
}

这是小提琴http://jsfiddle.net/HB7LU/4620/

具有recordController $ scope“record”属性还是从父作用域继承?我很困惑......

1 个答案:

答案 0 :(得分:3)

它是继承,而不是魔术:$scope.$parent实际上是$scope的原型:

$scope.$parent === $scope.__proto__ // true

引用the doc

  

在AngularJS中,子范围通常是原型继承自它的   父范围。

由于JS在查找未在其上找到的特定属性时会上升$scope对象的原型链,因此它将收集$scope.$parent上的一个属性。