要使用“$scope”表示法访问父控制器,只需使用“$scope.$parent”。
然而,“controller as vm”符号缺乏使其适用于某些行为的细节:
'$范围.$父级。vm'
app.controller('childCtrl', [
'$scope', function ($scope) {
var vmc = this;
// To protected access as vmc.parent
Object.defineProperty(vmc, 'parent', {
get: function () {
return $scope.$parent.vm;
}
});
}
]);
然而,更改父对象会对原始对象产生副作用,这可以在以下 angular.js 文档中理解。
JavaScript 原型继承 https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance
Example:
JS Bin 上的工作示例 http://jsbin.com/porot/3/edit?html,js,output
<section class="parent"
data-ng-controller="parentCtrl as vm">
<input data-ng-model="vm.name">
<!-- have to change the prefix after the 'as' not to have conflict -->
<section class="child"
data-ng-controller="childCtrl as vmc">
<input data-ng-model="vm.name">
<!-- same results -->
<input data-ng-model="$parent.vm.name">
<!-- same results -->
<input data-ng-model="vmc.parent.name">
<!-- same results -->
<button data-ng-click="vmc.changeName()">Change name</button>
</section>
</section>
(function(){
var app = angular.module('app', []);
app.controller('parentCtrl', [
'$scope', function ($scope) {
var vm = this;
vm.name = 'Julia';
}
]);
app.controller('childCtrl', [
'$scope', function ($scope) {
var vmc = this;
// To protected access as vmc.parent
Object.defineProperty(vmc, 'parent', {
get: function () {
return $scope.$parent.vm;
}
});
vmc.changeName = function(){
vmc.parent.name = 'Other ' + vmc.parent.name;
};
}
]);
})();