AT-2017
AT-2017

Reputation: 3149

Read Data From One Controller To Another

I've two controllers and two views in ASP.NET MVC project. My requirement is to pass data from one controller to another on ng-click that should reflect in another view (As well from another controller). Simple! I know, it could be done using service but I was preferring for testing purpose $broadcast and $on. So I tried the following:

app.controller('FirstController', function ($rootScope, $scope, productService) {
    $scope.showData = function (m) { //This is the event on which I'll get data in another controller as well in another view 
    alert(m); //This works and gets a name from the first view

    $rootScope.$broadcast('sample', $scope.m); //This is what I am using to deliver in another controller
    }
});

app.controller('SecondController', function ($scope) { 
    $scope.$on('sample', function (events, d) {
    alert(d);
})

In another view, I used something like this:

<div ng-app="app" ng-controller="SecondController">
   <ul class="nav navbar-nav">
      <li><a href="#"> Product {{ m }}</a></li>            
   </ul>
</div> 

Actually I am doing this all for demo purpose. But unfortunately, the above doesn't work. Am I missing something?

Update 1 - See the updated code:

app.controller('FirstController', function ($rootScope, $scope, productService) {
    $scope.showData = function (m) { //This is the event on which I'll get data in another controller as well in another view 
    alert(m); //This works and gets a name from the first view

      $timeout(function () {
        $scope.$broadcast('sample', m);
    });
  }
});

app.controller('SecondController', function ($scope) { 
    $scope.$on('sample', function (events, d) {
    alert(d);
})

Upvotes: 0

Views: 58

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77910

In your scenario it will not work in one case:

You call $rootScope.$broadcast('sample', $scope.m); before $scope.$on() is registered to listen on 'sample event a.e. before SecondController is created.

If you know that SecondController is created , you can wrap $rootScope.$broadcast('sample', $scope.m); with $timeout. a.e.:

$timeout(function(){
  $rootScope.$broadcast('sample', $scope.m); 
});

In this case $broadcast execution will be moved to end of events queue a.e. before next digest cycle that will be guarantee that Second Controller has been created and $scope.$on() is registered.

Upvotes: 1

james00794
james00794

Reputation: 1147

It's not entirely clear how you are using the second view & controller. Is it somewhere within the template that FirstController is assigned to? Seeing the template assigned to FirstController would help clarify. In any case, I've attached a simple plunker which shows how you can broadcast an event from a button click to a second controller.

https://plnkr.co/edit/KzNftVAYwPuCvsnflIz

Upvotes: 1

Related Questions