vesperae vesperae - 4 months ago 32
AngularJS Question

angularjs: updating $rootScope variables from a directive

what is the angular way of updating a rootScope variable from a directive?
im having trouble understanding how scopes work in directives...

so far i can only change the variable on the scope level.

app.run(['$rootScope', function($rootScope) {
$rootScope.foo = false;
}

app.directive('myDirective', [function(){
return {
restrict: 'A',
link: function(scope, elem, attrs) {
elem.bind('click', function() {
scope.$parent.foo = true;
scope.$parent.apply();
});
}
}
}]);

<!-- does not update foo -->
<p>{{ foo }}</p>

<!-- updates foo -->
<div my-directive><p>{{ foo }}</p></div>

Answer

If you need to access $rootScope anywhere you need to inject it and it will become available:

app.directive('myDirective', ['$rootScope', function($rootScope) {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            elem.bind('click', function() {
                $rootScope.foo = true;
                $rootScope.$apply();
            });
        }
    }   
}]);

There is also simpler another approach that doesn't require injection. Every scope object has access to the topmost $rootScope via $root reference. It means that you could also do this:

scope.$root.foo = true;
Comments