2016-06-25 1 views
1

基本的に2つのコントローラーを作成しました。最初のコントローラーがフォーム用で、もう1つが最初のコントローラーからの結果を使用する2つのコントローラー間でデータを共有するにはどうすればいいですか?

最初のコントローラは、検索バーからの入力を受け取り、$ http要求を行うだけです。コントローラからの検索機能は次のとおりです。 -

$scope.search = function() { 
    $scope.searchString && 
     searchService.search($scope.searchString).then(function(results) { 
     //what should I do here to share these results with the second controller? 
     }); 
     $scope.searchString = null; 
    } 

2番目のコントローラは、これらの結果を基本的に表示する必要があります。しかし、少なくとも私はそこにconsole.logに結果を得ることができますか?

基本的に検索があり、結果があります。

私は検索フォームを送信すると、結果はあなたがまた

$scope.search = function() { 
     $scope.searchString && 
      searchService.search($scope.searchString).then(function(results) { 
      //what should I do here to share these results with the second controller? 
      // if not working $emit then use $broadcast instead of $emit 
      $rootScope.$emit('someEvent', results); 


      }); 
      $scope.searchString = null; 
     } 


function displayController($scope) 
{ 
    $rootScope.$on('someEvent', function(event, args) { 
    console.log(args); 
    }); 

} 

答えて

1
$scope.search = function() { 
     $scope.searchString && 
      searchService.search($scope.searchString).then(function(results) { 
      //what should I do here to share these results with the second controller? 
      // if not working $emit then use $broadcast instead of $emit 
      $scope.$emit('someEvent', results); 


      }); 
      $scope.searchString = null; 
     } 


function otherController($scope) 
{ 
    $scope.$on('someEvent', function(event, args) { 
    console.log(args); 
    }); 

} 
+0

ありがとう。whats the diff $ scopeと$ rootScopeの間の違いは? – user1354934

+0

心配しないでください。今働いて!どうもありがとう! – user1354934

1

を表示する必要がありますサービスを作成して両方のコントローラに挿入する第1コントローラからフォームデータを設定する第2からのアクセス

module.service('FormDataHolder', function(){ 
    var formData; 

    this.setData = function(data) { 
     formData = data; 
    } 
    this.getData = function(){ 
     return formData; 
    } 
}) 
1

)あなたのコントローラは、あなたが$ rootScope.emitを(使用することができますネストされていないしたと仮定すると:(

+0

最初のコントローラでサブミットを処理した後、他のコントローラでgetDataを実行するにはどうすればよいですか? – user1354934

+0

私は基本的に私は受信するデータを "聴く"必要があります。 – user1354934

+1

角度サービスはシングルトンであるため、一度設定するとアプリ全体で利用できるようになります – lintu

関連する問題