2017-05-10 5 views
0

にParentController内ChildControllerを知らせるにはどうすれば以下のコードのようなコードを持っています。親領域内のボタンの1つがクリックされたときに子領域を表示したい。また、私はクリックされたボタンに基づいて別の関数を呼び出し、$scope.nameListの中にChildControllerを代入してデータを表示する必要があります。 私はこの仕事をするのがベストプラクティスであると思っていました。はAngularjs

+0

問題を解決できましたか? –

答えて

0

$scope$broadcastメソッドを使用するか、単純な$scope継承を使用できます。最初のアプローチから始めましょう。

HTML:

<div ng-controller="ParentController"> 
    <button ng-click="showSection('sectionA')">Show Section A</button> 
    <button ng-click="showSection('sectionB')">Show Section B</button> 
    <div ng-controller="ChildController"> 
     <section ng-if="showSection.sectionA">SOME CONTENT HERE</section> 
     <section ng-if="showSection.sectionB">SOME CONTENT HERE</section> 
    </div> 
</div> 

ParentController:

function ParentControler($scope) { 

    $scope.showSection = function (section) { 
     $scope.$broadcast('ParentController.showSection', section); 
    } 

} 

ChildController:

function ChildController($scope) { 

    $scope.showSection = { 
     sectionA: false, 
     sectionB: false 
    }; 

    $scope.$on('ParentController.showSection', (event, section) => { 
     $scope.showSection[section] = true; 
    } 

} 

それとも、VEの可能性単純に$scopeの継承を使用してください。この場合、十分な場合があります。

HTMLは前の例と同じです。

ParentController:

function ParentControler($scope) { 

    $scope.showSection = { 
     sectionA: false, 
     sectionB: false 
    }; 

    $scope.showSection = function (section) { 
     $scope.showSection[section] = true; 
    } 

} 

ChildController:

function ChildController($scope) { 

    // 

} 

それはあなたが長期的に達成しようとしているかに依存します。あなたがこの物語の王様をするための単純な解決策を探しているなら、$scopeの継承を使用してください。これらの2つのコントローラーの間でより精巧な通信が必要な場合は、イベントメソッドをオプトインすることができます。