Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 458
vesperae Avatar asked Apr 04 '14 19:04

vesperae


1 Answers

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;
like image 60
dfsq Avatar answered Sep 22 '22 02:09

dfsq