2

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?

Hardik Shah
  • 3,241
  • 2
  • 17
  • 36
zzangs33
  • 144
  • 11
  • You can use observer pattern to notify other controller see E.g. https://stackoverflow.com/questions/12576798/angularjs-how-to-watch-service-variables – Manish Balodia Jul 17 '18 at 07:16

1 Answers1

4

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.

Hardik Shah
  • 3,241
  • 2
  • 17
  • 36