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>
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;
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