javascriptangularjsangular-local-storage

AngularJS Sending event to another controller ($broadcast, $window.localStorage, etc.)


I want to send an event to another controller. To do this, I already know way using $rootScope.$broadcast or $scope.$emit then listen event using $scope.$on.

It is a general way, but my project initiates the controller in a different JS file.

//In broadcaster.js
function broadcasterCtrl(~~~~~, broadcasterService){
~~~~~~~~~~
}
function broadcasterService(~~~~~){
~~~~~~~~~~
}
angular
    .module('myApp')
    .service('broadcasterService', broadcasterService)
    .controller('broadcasterCtrl', broadcasterCtrl);

//In listener.js
function listenerCtrl(~~~~~, listenerService){
~~~~~~~~~~
}
function listenerService(~~~~~){
~~~~~~~~~~
}
angular
    .module('myApp')
    .service('listenerService', listenerService)
    .controller('listenerCtrl', listenerCtrl);

Because of this structure, the listener controller is initiated when the view(state) is called. So I used $window.localStorage.setItem('key', value), but I don't like it because, I think, it is very vulnerable.

Is there any idea using $broadcast? or is it secure using localStorage?


Solution

  • The best way to share information across multiple controllers are services since services are singletons it's easier to manage and isolate a scope/variables for that purpose.

    var app = angular.module('myApp', []);
        app.factory('datepickerinfo', function() {
            var keyValue;
    
            datepickerinfo.setKey = function(key) {
                keyValue = key;
            };
            datepickerinfo.getKey = function(){
            return keyValue;
        }
    
        return datepickerinfo;
    });
    

    And Inject it:

    function MyCtrl($scope, datepickerinfo) {
        $scope.dateKey = datepickerinfo.getKey();
    }
    

    LocalStorage:

    You can use local storage too. If you don't have any important data. (Important data means don't share user crucial information using local storage.) Otherwise, local storage is a good way. But, keep in mind you should handle local storage properly whenever any updation or deletion occurs.