Ad

Angular $broadcast Only Populating Data On Page Refresh

- 1 answer

I'm trying to pass data from a controller to a directive using $broadcast and $on.

Data only appears on the directive's HTML template when I refresh the page. It does not appear when I route to the controller template with the embedded directive.

The weird thing is, the data appears to have been received when I console log. I have tried using $timeout and angular.element(document).ready

Controller:

$http.getDashboardData(...).success(function(res) { 
      populateResults(res);
      ...
}

function populateResults (data) {
    $rootScope.safeApply(function () {
        $rootScope.$broadcast('show-results', data);
    });
}

Directive:

.directive('results',['$rootScope', function ($rootScope) {
    return {
        restrict: 'AE',
        scope: {},
        transclude: true,
        templateUrl: '/html/directives/results.html',
        link: function(scope, elem, attr){
        ...

$rootScope.$on('show-results', function(event, args) {
    angular.element(document).ready(function () {
        scope.init(args);
    });
});

scope.init = function (args) {

    console.log('ARGS', args); //Has data

    scope.questions = args;
};

Controller Page with embedded results directive:

<div class="myPage">
    <results></results>
</div>

Directive HTML:

<div>
    QUESTIONS: {{questions}} : //Empty array
</div>

Console Log: You can see it has data:

enter image description here


Routing sequence:

   .config:
        ...
        state('dashboard', {
            url : '/dashboard',
            templateUrl: '/html/pages/dashboard.html',
            controller: 'dashboardCtrl',
            resolve : {
                ProfileLoaded : function ($rootScope) {
                    return $rootScope.loadProfile();
                }
            }
        });

.run: This is to load profile if user refreshes the page:

    $rootScope.loadProfile = function () {
        return Me.getProfile({user_id : Cookies.get('user_id')}).success(function (res) {
            $rootScope.me = res;
        }).error(function (err) {
            console.log('Error: ', err);
        });
    };
Ad

Answer

In your directive link function, try to use scope.$on instead of $rootScope.$on, and use scope.init directly without document.ready

Ad
source: stackoverflow.com
Ad