4 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
盡管jm-的答案是處理這種情況的最佳方法,但為了將來(lái)參考,可以使用范圍的$$ childHead,$ childTail,$ nextSibling和$$ prevSibling成員來(lái)訪(fǎng)問(wèn)子范圍。這些沒(méi)有記錄在案,因此它們可能會(huì)在不通知的情況下進(jìn)行更改,但是如果您確實(shí)需要遍歷作用域,它們就在那。
// get $$childHead first and then iterate that scope's $$nextSiblings
for(var cs = scope.$$childHead; cs; cs = cs.$$nextSibling) {
// cs is child scope
}

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以嘗試以下方法:
$scope.child = {} //declare it in parent controller (scope)
然后在子控制器(作用域)中添加:
var parentScope = $scope.$parent;
parentScope.child = $scope;
現(xiàn)在,父母可以訪(fǎng)問(wèn)孩子的范圍了。

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊
一種可能的解決方法是使用init函數(shù)將子控制器注入到父控制器中。
可能的實(shí)現(xiàn):
<div ng-controller="ParentController as parentCtrl">
...
<div ng-controller="ChildController as childCtrl"
ng-init="ChildCtrl.init()">
...
</div>
</div>
ChildController您在哪里:
app.controller('ChildController',
['$scope', '$rootScope', function ($scope, $rootScope) {
this.init = function() {
$scope.parentCtrl.childCtrl = $scope.childCtrl;
$scope.childCtrl.test = 'aaaa';
};
}])
因此,現(xiàn)在ParentController您可以使用:
app.controller('ParentController',
['$scope', '$rootScope', 'service', function ($scope, $rootScope, service) {
this.save = function() {
service.save({
a: $scope.parentCtrl.ChildCtrl.test
});
};
}])
重要提示:
要正常工作,您必須使用指令ng-controller并使用as與我在html eg中相同的方式重命名每個(gè)控制器。
提示:在此過(guò)程中,
請(qǐng)使用chrome插件ng-inspector。它會(huì)幫助您理解樹(shù)。
- 4 回答
- 0 關(guān)注
- 616 瀏覽
添加回答
舉報(bào)