Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Directive - Receiving a broadcast from $rootscope

I have the following code,

HTML

<div ng-app="test">
    <div ng-controller="containerCtrl">
        <component data-module="components"></component>
    </div>
</div>

JS

var test = angular.module('test', []);

test.controller('containerCtrl', ['$scope', '$rootScope', function ($scope, $rootScope) {
    $scope.components = [];
    $scope.$on('onSomething', function(e) {
        $scope.components = $rootScope.config;
    });
}]);

test.directive('component', function () {
        var linkFn = function(scope, element, attrs) {
            scope.$on('onSomething', function(e) {
                console.log(scope, e, scope.module, e.currentScope.module);
                /*
                * Here 'module' is an array in both 'e' and 'scope' , but when I console it says [].
                */
                console.log("onSomething!");
            });
        };

        return {
            restrict: 'E',
            scope: {
                module: '=module'
            },
            link : linkFn
        };
    });

test.run(['$rootScope', '$timeout', function ($rootScope, $timeout) {
    $timeout(function(){
        $rootScope.config = [{id: "c1", width: 100, height: 100 }];
        $rootScope.$broadcast("onSomething", "");
    },5000);
    
}]);

Fiddle http://jsfiddle.net/vFncP/4/

Problem In run method, I have an ajax request which receives a configuration from the database. Once the request is complete, It is broadcast-ed to the scope level. Now the problem is, I am receiving the broadcast in a directive, when I console e or scope, I can see the module which has an array with data whereas when I console scope.module, it says []. I am not getting the error, am I doing something wrong?

Note: Adding a $scope.$watch might help, but I am trying to avoid $watch. Is there any other way to do it.

Thanks in advance

like image 929
moustacheman Avatar asked Nov 12 '13 12:11

moustacheman


Video Answer


1 Answers

A solution could be $digest to refresh scope values:

scope.$digest();

http://jsfiddle.net/Anthonny/vFncP/7/

like image 175
Anthonny Avatar answered Sep 19 '22 13:09

Anthonny