AngularJS - Communication Between Controllers & Directive

This is an example of how to use a custom service to facilitate communicate between multiple controllers using $rootscope as an event bus. I added in a directive just for fun.

by kwon

HTML

<div ng-controller='Example'>
    
    <div>Outside Of Directive</div>
    <p>{{authValue}}</p>
    
    <requires-authorization role='Admin' data-auth-value='authValue' data-unauth-value='unAuthValue'>
        <div>Inside directive. For Admin eyes only</div>
        <p>{{authValue}}</p>
    </requires-authorization>
    
    <div>Unauth'd Value</div>
    <p>{{unauthValue}}</p>
</div>

JavaScript

var app = angular.module('myModule', []);
app.controller('Example', function ($scope) {
    $scope.authValue = 2;
    $scope.unauthValue = -1;
});

app.factory('authService', function() {
    
    return {
    };
});

app.directive('requiresAuthorization', function () {
    return {
        template: '<div ng-if=\'iAmInRole\' ng-transclude></div>',
        restrict: 'E',
        transclude: true,
        scope: {
            role: '@',
            authValue: '=',
            unauthValue: '='
        },
        controller: function ($scope) {
            $scope.iAmInRole = true;
        }
    };
});