简体   繁体   中英

Broadcast and on not working as desired

I am trying to broad cast from 1 controller and watch for that variable on another controller and expecting some changes on the second controller. But its not working.

Below is the first controller code

$scope.gotoKBPage = function()
      {
         $location.path('/kb');
         $rootScope.$broadcast('newVar',{id: "123"});
      };

Below is the second controller code which is the /kb page

  $scope.newPage = function()
  {
      $scope.pernotes     = true; // this makes a section visible, but not happening
  };

   $rootScope.$on('newVar', function(event, data)
   {
    if(data)
    {
        $scope.newPage();
    }
   });

Is there anything i need to do explicitly for this to take effect.

Try this:

 $scope.newPage = function()
  {  
       $scope.$apply();
       $scope.pernotes     = true; // this makes a section visible, but not happening
  }

EDIT: i have tested. It should work without $apply too. Check this link: fiddle

I think you are using a wrong approach. If you only want to pass a parameter to the new controller, why not use a route parameter? See the example at the end of this documentation page

Note that in your code, you are registering the $on after you broadcast the message, so it is not going to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM