在另一个控制器中调用一个控制器的方法

angularjs- calling method of one controller in another

本文关键字:控制器 一个 方法 另一个 调用      更新时间:2023-09-26

嗨,我正在做一个项目,我有一个订阅/退订通知按钮。我在这个按钮上使用引导模式单击,如果用户选择ok,我执行所需的操作。一切都很好,只是在最后,为了刷新我的列表,我需要调用方法我的另一个控制器。我尝试使用$emit-$on,但无法使用。请帮助如何从ModalInstanceCtrl控制器调用myIssuesController的getassigneissues()方法。

angularjs代码

 //controller1
 var myIssuesController = function($scope, $sce, $http, cfpLoadingBar, deviceDetector, $filter, $modal, $log) {
$("#navMyIssues").addClass("active");
$scope.issueCommnets = null;
$scope.showComments = false;
$scope.Issues = [];
$scope.dateFormat = 'dd-MMM-yyyy';
$scope.dateTimeFormat = 'dd-MMM-yyyy h:mm:ss a';
$scope.selectedIssue = null;
$scope.statusName = null;
$scope.ProjectDetails = [];
$scope.selectedProject = null;
$scope.isVisible = false;
$scope.isVisibleReply = false;
$scope.notifiedMembers = null;
$scope.defaultProfileImagePath = "";
 //get all assigned issues
$scope.GetAssignedIssues = function() {
    alert('test');
    //$scope.issueCount = -1;
    $scope.issuesLoaded = false;
    $scope.issueDetailsLoaded = false;
    $scope.query = "";
    var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/GetAllAssignedIssues/';
    $http.post(url, []).success(function(data, status, headers, config) {
        if (data != '' || data.length == 0) {
            $scope.Issues = data;
            $scope.Issues = $filter('orderBy')($scope.Issues, 'CreatedOn', true);
            for (var count = 0; count < $scope.Issues.length; count++) {
                if ($scope.Issues[count].StatusName == "Pending") {
                    $scope.pendingIssueCount = $scope.pendingIssueCount + 1;
                } else if ($scope.Issues[count].StatusName == "In Progress") {
                    $scope.inprogressIssueCount = $scope.inprogressIssueCount + 1;
                } else if ($scope.Issues[count].StatusName == "Limitation") {
                    $scope.limitationIssueCount = $scope.limitationIssueCount + 1;
                } else if ($scope.Issues[count].StatusName == "Needs Research") {
                    $scope.needsresearchIssueCount = $scope.needsresearchIssueCount + 1;
                } else if ($scope.Issues[count].StatusName == "In Testing") {
                    $scope.intestingIssueCount = $scope.intestingIssueCount + 1;
                }
            }
            if (data.length != 0) {
                if ($scope.selectedIssue == null) {
                    $scope.selectedIssue = $scope.Issues[0];
                } else {
                    for (var count = 0; count < $scope.Issues.length; count++) {
                        if ($scope.Issues[count].Id == $scope.selectedIssue.Id) {
                            $scope.selectedIssue = $scope.Issues[count];
                        }
                    }
                }
            }
            $scope.issuesLoaded = true;
            $scope.showIssueDetails($scope.selectedIssue);
        } else {
            $scope.errors.push(data.error);
            //$scope.issueCount = -1;
        }
        if ($scope.isVisible == false) {
            $("#changedetailsbox").hide();
            $scope.isVisible = true;
        }
        if ($scope.isVisibleReply == false) {
            $("#postReplybox").hide();
            $scope.isVisibleReply = true;
        }
    }
    );
};
  $scope.$on("eventAssignedIssues", function (event,args) {
     alert('test1');
    $scope.GetAssignedIssues();
});
};
//controller 2
 var ModalInstanceCtrl = function ($scope, $modalInstance,modalHeader,modalBody,issueId,issueEmailId,$http) {
 $scope.modalHeader=modalHeader;
 $scope.modalBody=modalBody;
 $scope.issueId=issueId;
 $scope.issueEmailId=issueEmailId;
 $scope.ok = function () {
   if($scope.modalHeader=="Delete Issue")
   {
   }
   else if($scope.modalHeader=="Subscribe")
   {
     var issueNotification = { issueId: $scope.issueId, email: $scope.issueEmailId };
        var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/SubscribeIssueNotification/';
        $http.post(url, JSON.stringify(issueNotification)).success(function (data, status, headers, config) {
            if (data == "true" || data == true) {
                //$scope.GetAssignedIssues();
                 $scope.$root.broadcast("eventAssignedIssues",{});
            } else {
                $scope.errors.push(data.error);
            }
            $scope.showeditdesc = true;
        });
   }
   else if($scope.modalHeader=="Unsubscribe")
   {
   //for unsubscribing
        var issueId = $scope.issueId;
        var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/UnsubscribeIssueNotification/';
        $http.post(url, JSON.stringify({ issueId: issueId })).success(function (data, status, headers, config) {
            if (data == "true" || data == true) {
                //$scope.GetAssignedIssues();
                 $scope.$root.broadcast("eventAssignedIssues",{});
            } else {
                $scope.errors.push(data.error);
            }
            $scope.showeditdesc = true;
        });
   }
    $modalInstance.close();
};
$scope.cancel = function () {
    $modalInstance.dismiss('cancel');
};
 };

如果要在两个同级控制器之间通信,请使用$ rootscope . broadcast ()请参考这个链接精彩的解释http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

  • 使用服务,工厂,价值将为您服务的目的共享数据
  • 使用$emit和$broadcast将为您完成这项工作,如下所示

      function firstCtrl($scope,$rootScope) {
        $scope.broadcast = function(bcMsg){
         $scope.broadcastMsg = bcMsg;
         $rootScope.$broadcast('broadC',$scope.broadcastMsg);
      }  
       $rootScope.$on('emitC',function(events,data){
          $scope.emitMsg = data;
       });
    }
    
     //second controller
      myApp.controller('secondCtrl',secondCtrl);
       //inject dependencies
      secondCtrl.$inject = ["$scope","$rootScope"];
     function secondCtrl($scope,$rootScope) {
     $scope.$on('broadC',function(events,data){
        $scope.broadcastMsg=data;
    });
         $rootScope.$on('emitC',function(events,data){
            $scope.emitMsg = data;
          });
        }
    
    http://jsfiddle.net/shushanthp/w4pwkkcq/

  • 使用指令在控制器之间共享数据也可以在指令中使用require使用"在指令中要求父控制器

要理解事件,请阅读本文-在这里输入链接描述我已经找到了@Shubham Nigam帮助的解决方案,所以感谢他-首先我们需要在两个控制器中定义$rootScope,并使用$rootScope使用$on和$broadcast。这是我更新的代码

答案

  //controller1
 var myIssuesController = function($rootScope,$scope, $sce, $http, cfpLoadingBar, deviceDetector, $filter, $modal, $log) {
$("#navMyIssues").addClass("active");
$scope.issueCommnets = null;
$scope.showComments = false;
$scope.Issues = [];
$scope.dateFormat = 'dd-MMM-yyyy';
$scope.dateTimeFormat = 'dd-MMM-yyyy h:mm:ss a';
$scope.selectedIssue = null;
$scope.statusName = null;
$scope.ProjectDetails = [];
$scope.selectedProject = null;
$scope.isVisible = false;
$scope.isVisibleReply = false;
$scope.notifiedMembers = null;
$scope.defaultProfileImagePath = "";
 //get all assigned issues
$scope.GetAssignedIssues = function() {
    alert('test');
    //$scope.issueCount = -1;
    $scope.issuesLoaded = false;
    $scope.issueDetailsLoaded = false;
    $scope.query = "";
    var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/GetAllAssignedIssues/';
    $http.post(url, []).success(function(data, status, headers, config) {
        if (data != '' || data.length == 0) {
            $scope.Issues = data;
            $scope.Issues = $filter('orderBy')($scope.Issues, 'CreatedOn', true);
            for (var count = 0; count < $scope.Issues.length; count++) {
                if ($scope.Issues[count].StatusName == "Pending") {
                    $scope.pendingIssueCount = $scope.pendingIssueCount + 1;
                } else if ($scope.Issues[count].StatusName == "In Progress") {
                    $scope.inprogressIssueCount = $scope.inprogressIssueCount + 1;
                } else if ($scope.Issues[count].StatusName == "Limitation") {
                    $scope.limitationIssueCount = $scope.limitationIssueCount + 1;
                } else if ($scope.Issues[count].StatusName == "Needs Research") {
                    $scope.needsresearchIssueCount = $scope.needsresearchIssueCount + 1;
                } else if ($scope.Issues[count].StatusName == "In Testing") {
                    $scope.intestingIssueCount = $scope.intestingIssueCount + 1;
                }
            }
            if (data.length != 0) {
                if ($scope.selectedIssue == null) {
                    $scope.selectedIssue = $scope.Issues[0];
                } else {
                    for (var count = 0; count < $scope.Issues.length; count++) {
                        if ($scope.Issues[count].Id == $scope.selectedIssue.Id) {
                            $scope.selectedIssue = $scope.Issues[count];
                        }
                    }
                }
            }
            $scope.issuesLoaded = true;
            $scope.showIssueDetails($scope.selectedIssue);
        } else {
            $scope.errors.push(data.error);
            //$scope.issueCount = -1;
        }
        if ($scope.isVisible == false) {
            $("#changedetailsbox").hide();
            $scope.isVisible = true;
        }
        if ($scope.isVisibleReply == false) {
            $("#postReplybox").hide();
            $scope.isVisibleReply = true;
        }
    }
    );
};
 $rootScope.$on('eventAssignedIssues', function (event, args) {
    $scope.GetAssignedIssues();
});
};
//controller 2
 var ModalInstanceCtrl = function ($rootScope,$scope, $modalInstance,modalHeader,modalBody,issueId,issueEmailId,$http) {
 $scope.modalHeader=modalHeader;
 $scope.modalBody=modalBody;
 $scope.issueId=issueId;
 $scope.issueEmailId=issueEmailId;
 $scope.ok = function () {
   if($scope.modalHeader=="Delete Issue")
   {
   }
   else if($scope.modalHeader=="Subscribe")
   {
     var issueNotification = { issueId: $scope.issueId, email: $scope.issueEmailId };
        var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/SubscribeIssueNotification/';
        $http.post(url, JSON.stringify(issueNotification)).success(function (data, status, headers, config) {
            if (data == "true" || data == true) {
                //$scope.GetAssignedIssues();
                 $rootScope.$broadcast('eventAssignedIssues');
            } else {
                $scope.errors.push(data.error);
            }
            $scope.showeditdesc = true;
        });
   }
   else if($scope.modalHeader=="Unsubscribe")
   {
   //for unsubscribing
        var issueId = $scope.issueId;
        var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/UnsubscribeIssueNotification/';
        $http.post(url, JSON.stringify({ issueId: issueId })).success(function (data, status, headers, config) {
            if (data == "true" || data == true) {
                //$scope.GetAssignedIssues();
                 $rootScope.$broadcast('eventAssignedIssues');
            } else {
                $scope.errors.push(data.error);
            }
            $scope.showeditdesc = true;
        });
   }
    $modalInstance.close();
};
$scope.cancel = function () {
    $modalInstance.dismiss('cancel');
};
 };