简体   繁体   English

广播且无法正常工作

[英]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 下面是第二个控制器代码,即/ kb页面

  $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. 它也应该在没有$ apply的情况下工作。 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? 如果只想将参数传递给新控制器,为什么不使用route参数呢? 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. 请注意,在您的代码中,您是在广播消息后注册$on的,因此它将无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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