AngularJS $broadcast and $on

angularjsangularjs-scope

is there a way to make the $broadcast propagate the variable to the $on during initialization phase?

<div ng-app='test'>
    <div ng-controller='testCtrl'> <span>{{testContent}}</span> 
    </div>
    <div ng-controller="testCtrl2">
        <input type='text' ng-change="updateContent()" ng-model="testContent2" />
    </div>
</div>

 

var app = angular.module('test', []);
app.factory('sharedContent', function ($rootScope) {
    var standardContent;
    var resizeProportion;
    return {
        setStandardContent: function (newStandardContent) {
            standardContent = newStandardContent;
            $rootScope.$broadcast('updateContent');
            console.log('broadcast');
        },
        getStandardContent: function () {
            return standardContent;
        },
        setResizeProportion: function (newResizeProportion) {
            $rootScope.$broadcast('updateResizeProportion');
        },
    }
});
app.run(function (sharedContent) {
    sharedContent.setStandardContent('haha');
});

function testCtrl($scope, sharedContent) {
    $scope.testContent;
    $scope.$on('updateContent', function () {
        console.log('receive');
        $scope.testContent = sharedContent.getStandardContent();
    });
}

function testCtrl2($scope, sharedContent) {
    $scope.testContent2 = 'test';
    $scope.updateContent = function () {
        sharedContent.setStandardContent($scope.testContent2);
    };
}

Sample fiddle : http://jsfiddle.net/jiaming/NsVPe/

The span will display the value as the input changes, which is due to the ng-change function.

However, at initialization phase, the value "haha" was not propagated to the $scope.testContent and thus, nothing was shown at first runtime. Is there a way to make the value "haha" appear at the first runtime?

Thank you.

Best Solution

Just provide a little delay using $timeout function. Just update the code in the factory it will start working.

Please refer the code below for the factory:

app.factory('sharedContent', function ($rootScope,$timeout) {
    var standardContent;
    var resizeProportion;
    return {
        setStandardContent: function (newStandardContent) {
            standardContent = newStandardContent;
            $timeout(function(){
              $rootScope.$broadcast('updateContent');
            },0)
             console.log('broadcast');
        },
        getStandardContent: function () {
            return standardContent;
        },
        setResizeProportion: function (newResizeProportion) {
            $rootScope.$broadcast('updateResizeProportion');
        },
    }
});