vesperae
vesperae

Reputation: 1291

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>

Upvotes: 6

Views: 4776

Answers (1)

dfsq
dfsq

Reputation: 193261

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;

Upvotes: 9

Related Questions