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

為{幸葍}努か 提交于 2019-12-10 23:31:37

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/51374003/angularjs-sending-event-to-another-controller-broadcast-window-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!