angularjsscopebroadcastrootscope

$rootScope.$broadcast is not updating on page reload?


First Controller:

$rootScope.$broadcast("CallParentMethod", {});

Second Controller:

$rootScope.$on("CallParentMethod", function() {
    $scope.getUserDetails();
})
$scope.getUserDetails = function() {
    HttpService.get("/customer/" + nationalId).then(function(resp) {
        if (resp.status == 'success') {
            console.log(resp.result)
            $rootScope.county_name = angular.copy(resp.result.county)
            $rootScope.campaign_name = angular.copy(resp.result.campaign)
            console.log($rootScope.campaign_name)
        }
    });
};

Solution

  • there's a mix of $scopes there

    there is this event fired

    $rootScope.$broadcast("CallParentMethod", {});
    

    therefore you should be listening for this event in a child $scope, but you're listening to it in $rootScope

    $rootScope.$on("CallParentMethod", function() {
        $scope.getUserDetails();
    })
    

    you might want to listen for it in the same scope in which getUserDetails() is defined

    $scope.$on("CallParentMethod", function() {
        $scope.getUserDetails();
    })
    

    Another hint: if you don't need to pass any parameters, you can ignore the empty object {} when $broadcasting

    $rootScope.$broadcast("CallParentMethod")