AngularJS将事件发送到另一个控制器($ broadcast,$ window.localStorage等) [英] AngularJS Sending event to another controller ($broadcast, $window.localStorage, etc.)

查看:225
本文介绍了AngularJS将事件发送到另一个控制器($ broadcast,$ window.localStorage等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将事件发送到另一个控制器.为此,我已经知道使用 $ rootScope.$ broadcast $ scope.$ emit 的方式,然后使用 $ scope.$ on 监听事件.

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.

这是一种通用方法,但是我的项目在另一个JS文件中启动了控制器.

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);

由于这种结构,在调用view(state)时将启动侦听器控制器.因此,我使用了 $ window.localStorage.setItem('key',value),但我不喜欢它,因为我认为它非常脆弱.

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.

使用 $ broadcast 有什么主意吗?还是使用localStorage安全吗?

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

推荐答案

在多个控制器之间共享信息的最佳方法是服务,因为服务是单例,因此更易于管理和隔离作用域/变量.

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;
});

然后注入:

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

本地存储:

您也可以使用本地存储.如果您没有任何重要数据.(重要数据意味着不要使用本地存储共享用户关键信息.)否则,本地存储是一个好方法.但是,请记住,每当发生任何更新或删除时,您都应该正确处理本地存储.

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.

这篇关于AngularJS将事件发送到另一个控制器($ broadcast,$ window.localStorage等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆