若html如下:
<div ng-controller="ParentCtrl"> <div ng-controller="ChildCtrl"> </div></div>
你可以如此访问父元素:
function ParentCtrl($scope) { $scope.cities = ["NY", "Amsterdam", "Barcelona"];}function ChildCtrl($scope) { $scope.parentcities = $scope.$parent.cities;}
还有一个更好的方法:因为子元素可以继承父元素的内容,因此你不必调用$parent,上面的实例可以如此重写:
function ParentCtrl($scope) { $scope.cities = ["NY","Amsterdam","Barcelona"];}function ChildCtrl($scope) { $scope.parentCities = $scope.cities;}
其他方式:
HTML
<div ng-app ng-controller="ParentCtrl as pc"> <div ng-controller="ChildCtrl as cc"> <pre>{{cc.parentCities | json}}</pre> <pre>{{pc.cities | json}}</pre> </div></div>
JS
function ParentCtrl() { var vm = this; vm.cities = ["NY", "Amsterdam", "Barcelona"];}function ChildCtrl() { var vm = this; ParentCtrl.apply(vm, arguments); // Inherit parent control vm.parentCities = vm.cities;}
如果使用别名,你也可以通过下面这种方式访问父元素内容:
function ChildCtrl($scope) { var vm = this; vm.parentCities = $scope.pc.cities; // note pc is a reference to the "ParentCtrl as pc"}
如你所见,有不同方式访问父元素
function ParentCtrl() { var vm = this; vm.cities = ["NY", "Amsterdam", "Barcelona"];} function ChildCtrl($scope) { var vm = this; ParentCtrl.apply(vm, arguments); vm.parentCitiesByScope = $scope.pc.cities; vm.parentCities = vm.cities;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script><div ng-app ng-controller="ParentCtrl as pc"> <div ng-controller="ChildCtrl as cc"> <pre>{{cc.parentCities | json}}</pre> <pre>{{cc.parentCitiesByScope | json }}</pre> <pre>{{pc.cities | json}}</pre> </div></div>
可参考:http://stackoverflow.com/questions/21453697/angularjs-access-parent-scope-from-child-controller