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
A solution could be $digest to refresh scope values:
scope.$digest();
http://jsfiddle.net/Anthonny/vFncP/7/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With