簡體   English   中英

$ broadcast在Angularjs中不起作用

[英]$broadcast is not working in Angularjs

我正在使用兩個控制器。 當一個控制器發生變化時,應立即在另一個控制器中進行更改。 我正在使用$ broadcast事件來實現這個目標。

我的代碼:

我的第一控制器

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;
  })
 } 
});

我的第二控制員:

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(),一切似乎都正常。 但是在SidemenuController中,我沒有得到任何數據。 我的代碼中有錯誤嗎?

更新:

我的觀點 :

 <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>

如果你想使用$ brodcast將數據從一個控制器發送到另一個控制器brodcast不是使用$rootscope.$broadcast

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

第二控制器

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;
    });
});

注意:不要使用$rootscope.$on作為監聽器,因為$ rootscope監聽器不會被銷毀。 相反,它將創建偵聽器堆棧

如果要將一個控制器事件調用到另一個控制器事件,則有四種方法可用:

  • $rootScope.$broadcast()如果您的控制器不在父/子關系中。
  • 如果您的第二個控制器(此處觸發的事件)是父級,您可以使用$scope.$broadcast();
  • 如果您的第二個控制器(此處觸發的事件)是一個孩子,您可以使用$scope.$emit();
  • 解決此問題的最佳方法是使用服務 - > 使用服務在控制器之間共享數據的示例

注意:您需要銷毀$rootScope.$on()偵聽器手動避免堆疊事件。 這個$ rootScope。$ on vs $ scope。$ on之間的差異 你需要在$ scope $ destroy事件中取消綁定$ scope。$ on嗎? 將幫助您了解使用事件的基本知識。

視圖

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

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);
});

> 演示小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM