angularjs使用$ on和$ broadcast在主控制器与另一个控制器之间进行通信

时间:2017-03-09 11:16:30

标签: angularjs asp.net-mvc master-pages

我正在尝试在两个角度控制器之间设置通信(服务不是一个选项)。我拼命地失败了。

这是我的一些代码...... 我尝试使用$ emit和$ broadcast

invoiceApp.controller('masterReportConrtoller', ['$scope', '$location', 'authService', 'usSpinnerService', 'dateService', 'settingsService','$rootScope',
function ($scope, $location, authService, usSpinnerService, dateService, settingsService, $rootScope ) 
 ////Is User Valid
    ////
    //$rootScope.$on("masterReportConrtoller", function () {
    //        $scope.parentmethod();
    //    });
    //$scope.parentmethod = function () {
    //    //
    $scope.masterReportConrtoller.getUserDetails = function () {
        debugger;
            settingsService.getUserDetails().then(function (response) {
                var loginData = {
                    userName: response.d.user.Email,
                    password: response.d.user.UserPassword

                };
            authService.login(loginData).then(function (response) {
                debugger;
                $scope.Limit = response.d.organization.Limit;
            });
            $scope.Limit = response.d.organization.Limit;
            $scope.DocumentUsage = response.d.organization.DocumentUsage;
            $scope.ExpirationDate = $scope.DateConvertfromJson(response.d.organization.ExpirationDate);
            var fullDate = new Date();
            if (fullDate <= $scope.ExpirationDate) {
                $scope.ISvalidUser = false;
                $rootScope.$broadcast('masterReportConrtoller', false);
            }
            else {
                $rootScope.$broadcast('masterReportConrtoller', true);
            }
        });
    }   
}]);


invoiceApp.controller('InvoiceController', ['$scope', '$location', '$cookieStore', 'documentService', 'dialogs', 'usSpinnerService', 'settingsService', 'associatedEmailsService', '$rootScope',
function ($scope, $location, $cookieStore, documentService, dialogs, usSpinnerService, settingsService, associatedEmailsService, $rootScope) {


 $rootScope.$on('masterReportConrtoller');}

2 个答案:

答案 0 :(得分:1)

根据您的父子控制器关系,您可以在代码中使用$scope.$broadcast$scope.$on

尝试这样的事情:

//masterReportConrtoller
$scope.$broadcast("myCustomEvent", { isValidUser: false });

//InvoiceController
$scope.$on("myCustomEvent" , function(event, data){
   //do something with data
});

请注意,如果masterReportConrtoller是父控制器且InvoiceController是子控制器,则此方法有效。如果不是这种情况,请使用$rootScope.$broadcast$rootScope.$on

您可以找到更多详情here

答案 1 :(得分:0)

您可以使用$localStorage$stateParams$cookies甚至......我通常更喜欢$stateParams向状态和控制器发送值和对象。

$state.go('state2', { someParam : 'broken magic' });

使用控制器中的$stateParams读取文件。可以找到详细信息here