简体   繁体   English

$ broadcast在Angularjs中不起作用

[英]$broadcast is not working in Angularjs

I am using two controllers. 我正在使用两个控制器。 When changes happen in one controllers it should get changed immediately in the other controller. 当一个控制器发生变化时,应立即在另一个控制器中进行更改。 I am using the $broadcast event to achive this. 我正在使用$ broadcast事件来实现这个目标。

My code: 我的代码:

My First controller 我的第一控制器

app.controller('configurationCtrl', function($scope, $http,Notification,$rootScope,$cookies) {
$scope.awssubmit=function(){
  $scope.page_loader=true
  $http.post("/insert_config_details",$scope.userdata).then(function(List){
   if(List){
   $scope.page_loader=false;
   $cookies.put("bucket",$scope.userdata.bucket_name)
   $scope.$broadcast('eventEmitedName', 'Some data');
   Notification.success('<span class="glyphicon glyphicon-ok"></span> <strong>AWS Configuration details updated successfully.</strong>');
}
  else{
  $scope.page_loader=false;
  Notification.error('<span class="glyphicon glyphicon-ok"></span> <strong>Error!!! Please try again later.</strong>');
  }
  $scope.awssave = false;
  $scope.awstext=true;
  })
 } 
});

My Second Controller: 我的第二控制员:

app.controller('SidemenuController', function($scope, $http,$location,BucketService) 
 {

      $scope.$on('eventEmitedName', function (event, data) {
         console.log("Called"); //I am not getting this 
    value
        console.log(data); // 'Some data' // I am not getting this 
    value
      });
});

aws_submit() is called from my view and everything seems to work fine. 从我的视图中调用aws_submit(),一切似乎都正常。 But in SidemenuController I am not getting any data. 但是在SidemenuController中,我没有得到任何数据。 Is there any mistake in my code? 我的代码中有错误吗?

Update: 更新:

My view : 我的观点 :

 <form id="awsform" method="post" name="awsform" class="form-horizontal" novalidate>
                    <div class="col-sm-6 four_module_config">
                      <div class="account_settings">
                        <div class="col-sm-12 heading_config" ng-hide="awssave">
                          <h4 class="sub_title col-sm-11" style="border-bottom:none">AWS S3 Configurations</h4>
                          <% if(valid_role[1]) { %>
                            <div class="action col-sm-1">
                              <span class="actico editrole" ng-click="editaws()">
                        <a href='javascript:void(0)' ></a>
                        </span>
                            </div>
                            <% } %>
                        </div>
                        <div class="col-sm-12 heading_config" ng-show="awssave">
                          <h4 class="sub_title col-sm-9" style="border-bottom:none">AWS S3 Configurations</h4>
                          <div class="action col-sm-3 close_config">
                            <button  type="button" class="site_btn submit_btn save_config col-sm-2" id="submit" ng-show="awstest"
                              ng-click="verifyaws()">Test</button>
                            <button type="button" class="site_btn submit_btn save_config col-sm-2" id="submit" ng-show="submitawssave"
                              ng-click="awssubmit()">Submit</button>
                            <button type="button" class="site_btn submit_btn save_config col-sm-2" id="submit" ng-click="closeaws()">Cancel</button>
                          </div>
                        </div>
                        <div class="ipfield  col-md-8 hint_txt_conf">
                          *Enter your AWS access Key, S3 Bucket name configured in your AWS Environment. Which is used to store your document in the
                          cloud.
                        </div>
                        <div class="ipfield first_ipfield">
                          <div class="col-md-8">
                            <label for="name" class="usrlabel">AWS access key <span class="mandat">*</span></label>
                            <input type="password" ng-disabled="awstext" ng-model="userdata.key" required name="key" class="txt_box" id="key" placeholder="Enter AWS access key">
                            <span toggle="#key" class="fa fa-fw fa-eye field_icon toggle-password"></span>
                          </div>
                        </div>
                        <div class="ipfield">
                          <div class="col-md-8">
                            <label for="name" class="usrlabel">AWS Secret Key <span class="mandat">*</span></label>
                            <input type="password" ng-disabled="awstext" ng-model="userdata.secretkey" required name="secretkey" class="txt_box" id="secretkey" placeholder="Enter AWS Secret Key">
                            <span toggle="#secretkey" class="fa fa-fw fa-eye field_icon toggle-password"></span>
                          </div>
                        </div>
                        <div class="ipfield">
                          <div class="col-md-8">
                            <label for="name" class="usrlabel">AWS Region Code <span class="mandat">*</span></label>
                            <input type="text" ng-disabled="awstext" ng-model="userdata.region" required name="region" class="txt_box" id="region" placeholder="Enter AWS Region Code">

                          </div>
                        </div>
                        <div class="ipfield">
                          <div class="col-md-8">
                            <label for="name" class="usrlabel">AWS Bucket Name <span class="mandat">*</span></label>
                            <input type="text" ng-disabled="awstext" ng-model="userdata.bucket_name" required name="bucket_name" class="txt_box" id="bucket"
                              placeholder="Enter  AWS Bucket Name">
                          </div>
                        </div>
                      </div>
                    </div>
                  </form>

If you want to send data from one controller to another controller using $ brodcast than use $rootscope.$broadcast 如果你想使用$ brodcast将数据从一个控制器发送到另一个控制器brodcast不是使用$rootscope.$broadcast

$rootScope.$broadcast('eventEmitedName', 'Some data');

Second Controller 第二控制器

app.controller('SidemenuController', function($scope, $http,$location,BucketService) {
    $scope.$on('eventEmitedName', function (event, data) {
        console.log("Called");
        console.log(data); // 'Some data'
        $scope.bucket = data;
    });
});

Note: Do not use $rootscope.$on as listener because $rootscope listener are not destroyed . 注意:不要使用$rootscope.$on作为监听器,因为$ rootscope监听器不会被销毁。 Instead it will create listeners stack 相反,它将创建侦听器堆栈

If you want to call one controller event into another there are four methods available: 如果要将一个控制器事件调用到另一个控制器事件,则有四种方法可用:

  • $rootScope.$broadcast() if your controller are not in a parent / child relation. $rootScope.$broadcast()如果您的控制器不在父/子关系中。
  • If your second controller (event fired here) is a parent you can use $scope.$broadcast(); 如果您的第二个控制器(此处触发的事件)是父级,您可以使用$scope.$broadcast();
  • If your second controller (event fired here) is a child you can use $scope.$emit(); 如果您的第二个控制器(此处触发的事件)是一个孩子,您可以使用$scope.$emit();
  • The best way to solve this would be to use a service -> Example of using a service to share data between controllers . 解决此问题的最佳方法是使用服务 - > 使用服务在控制器之间共享数据的示例

Note: You need to destroy $rootScope.$on() listeners manually avoid stacking events. 注意:您需要销毁$rootScope.$on()侦听器手动避免堆叠事件。 This Difference between $rootScope.$on vs $scope.$on and this Do you need to unbind $scope.$on in $scope $destroy event? 这个$ rootScope。$ on vs $ scope。$ on之间的差异 你需要在$ scope $ destroy事件中取消绑定$ scope。$ on吗? will help you understand the basics of using events. 将帮助您了解使用事件的基本知识。

View 视图

<div ng-controller="MyCtrl">
  <button ng-click="broadcast()">
    broadcast
  </button>
</div>
<div ng-controller="MySecondCtrl">
  {{ test }}
</div>

AngularJS application AngularJS应用程序

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope, $rootScope) {
  $scope.broadcast = function() {
    $rootScope.$broadcast('test', 'testit');
  }
});

myApp.controller('MySecondCtrl', function($scope, $rootScope) {
  var registerScope = $rootScope.$on('test', function(test, args) {
    console.log(args);
    $scope.test = args;
  });

  // clean up, destroy event when controller get destroyed. 
  $scope.$on('$destroy', registerScope);
});

> demo fiddle > 演示小提琴

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

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