AngularJSは子コントローラから親スコープにアクセスする 質問する

AngularJSは子コントローラから親スコープにアクセスする 質問する

私はコントローラーを次のように設定しましたdata-ng-controller="xyzController as vm"

親/子のネストされたコントローラーを使用するシナリオがあります。 を使用してネストされた HTML 内の親プロパティにアクセスすることに問題はありません$parent.vm.propertyが、子コントローラー内から親プロパティにアクセスする方法がわかりません。

$scope を挿入してから を使用しようとしました$scope.$parent.vm.propertyが、機能しません。

誰かアドバイスをくれませんか?

ベストアンサー1

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;
}

ビューから親コントローラーにアクセスする場合は、次のようにする必要があります。

<div ng-controller="xyzController as vm">
   {{$parent.property}}
</div>

jsFiddle を参照してください:http://jsfiddle.net/2r728/

アップデート

実際には、親コントローラーで定義したので、cities子コントローラーはすべてのスコープ変数を継承します。したがって、理論的には を呼び出す必要はありません$parent。上記の例は次のように記述することもできます。

function ParentCtrl($scope) {
    $scope.cities = ["NY","Amsterdam","Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentCities = $scope.cities;
}

AngularJSのドキュメントではこのアプローチを採用しています。ここについてさらに詳しく読むことができます$scope

もう一つのアップデート

これは元の投稿者に対するより良い回答だと思います。

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;
}

メソッドを使用すると、controller as次のように親スコープにアクセスすることもできます。

function ChildCtrl($scope) {
    var vm = this;
    vm.parentCities = $scope.pc.cities; // note pc is a reference to the "ParentCtrl as pc"
}

ご覧のとおり、 にアクセスするにはさまざまな方法があります$scopes

更新されたフィドル

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>

おすすめ記事