AngularJS コントローラーは別のコントローラーを呼び出すことができますか? 質問する

AngularJS コントローラーは別のコントローラーを呼び出すことができますか? 質問する

1 つのコントローラーで別のコントローラーを使用することは可能ですか?

例えば:

MessageCtrlこの HTML ドキュメントは、ファイル内のコントローラーによって配信されたメッセージを単純に印刷しますmessageCtrl.js

<html xmlns:ng="http://angularjs.org/">
<head>
    <meta charset="utf-8" />
    <title>Inter Controller Communication</title>
</head>
<body>
    <div ng:controller="MessageCtrl">
        <p>{{message}}</p>
    </div>

    <!-- Angular Scripts -->
    <script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
    <script src="js/messageCtrl.js" type="text/javascript"></script>
</body>
</html>

コントローラー ファイルには次のコードが含まれています。

function MessageCtrl()
{
    this.message = function() { 
        return "The current date is: " + new Date().toString(); 
    };
}

これは単に現在の日付を印刷します。

DateCtrl特定の形式で日付を に返す別のコントローラーを追加する場合MessageCtrl、これをどのように実行すればよいでしょうか? DI フレームワークは、XmlHttpRequestsと サービスへのアクセスに関係しているようです。

ベストアンサー1

コントローラー間で通信する方法は複数あります。

おそらく最も良いのは、サービスを共有することです。

function FirstController(someDataService) 
{
  // use the data service, bind to template...
  // or call methods on someDataService to send a request to server
}

function SecondController(someDataService) 
{
  // has a reference to the same instance of the service
  // so if the service updates state for example, this controller knows about it
}

別の方法は、スコープでイベントを発行することです。

function FirstController($scope) 
{
  $scope.$on('someEvent', function(event, args) {});
  // another controller or even directive
}

function SecondController($scope) 
{
  $scope.$emit('someEvent', args);
}

どちらの場合も、任意のディレクティブを使用して通信できます。

おすすめ記事