I am trying to interact with the rootScope in order to make a modal appear. I have a very basic directive that I am trying to use rootScope paired with an ng-show.
Here is the code for the directive:
.directive('modal', ['$rootScope', function ($rootScope) {
return {
restrict: 'A',
templateUrl: 'view/templates/modal-confirm.tpl.html',
link: function (scope, element, attrs) {
console.log(scope);
element.on('click', function() {
scope.$root.confirmModal.isVisible = true;
console.log('open modal');
});
}
}
}])
When I log the scope variable, it is showing me as having $root updated with the isVisible: true however, my modal doesn't appear. If I change the scope.$root.confirmModal.isVisible = true; to $rootScope.confirmModal.isVisible = true; I get the same result, the console.log is working but no modal appearing.
This is the code for the modal template:
<!-- Confirm Modal Template -->
<div ng-if="$root.confirmModal.isVisible" class="overlay">
<div class="overlay-content extended">
<span>{{ $root.confirmModal.content }}</span>
<div class="buttons">
<button ng-click="$root.confirmModal.isVisible = false;" class="btn btn-default half">Cancel</button>
</div>
</div>
</div>
Is it not possible to interact with the $rootScope in a directive?
Updated code using scope instead of $rootScope:
.directive('modal', ['$rootScope', function ($rootScope) {
return {
restrict: 'A',
templateUrl: 'view/templates/modal-confirm.tpl.html',
link: function (scope, element, attrs) {
scope.isVisible = false;
element.on('click', function() {
scope.isVisible = true;
console.log(scope);
console.log('open modal');
});
}
}
}])
<!-- Confirm Modal Template -->
<div ng-if="isVisible" class="overlay">
<div class="overlay-content extended">
<span>hello world</span>
</div>
</div>
Same result however.
scope.$root.confirmModal.isVisibleto justscope.isVisibleand$root.confirmModal.isVisibletoisVisible, init withscope.isVisible = false;it does not appear on click. It is being set toisVisible: trueif I look at thescopeafter the on-click function. What am I doing wrong?