Angular 在自己的控制器中处理事件
Angular handle events in own Controller
我正在开发一个用 AngularJS 编写的 Electron 应用程序。在 Electron 应用程序的主进程中,我正在监听 DownloadItem 事件。因此,每次用户下载文件时,都会触发该事件。在我的 Main.js 中,我有以下代码。
win.webContents.session.on('will-download', (event, item, webContents) => {
item.once('done', (event, state) => {
if (state === 'completed') {
win.webContents.send('download-message', 'completed', item.getSavePath());
} else if (state === 'interrupted') {
win.webContents.send('download-message', 'failed');
}
})
});
在 Angular 方面,我在 "main" 控制器(代表应用程序的起点)中等待这样的事件。所以,这里我有一些看起来像这样的代码:
const { ipcRenderer } = require('electron');
ipcRenderer.on('download-message', function (event, method, filepath) {
if (method === 'completed') {
// Do something interesting
} else if (method === 'failed') {
// Do something interesting
}
});
这工作得很好,但在主应用程序控制器中处理所有这些事件感觉有点难看。我想将它分离到它自己的控制器(例如 downloadController)。
我考虑过在它自己的服务(例如 downloadsService)中监听这个事件,但是因为我想操纵应用程序的视图(例如显示一些 success/failure 消息),我不认为这是该功能的合适位置。
所以,我正在寻找一种将此功能分离到特定控制器的好方法。
也许我只是不太了解 Angular 及其控制器的概念,所以任何建议都会很有帮助。
提前致谢!
您可以在用于修改视图的任何控制器中处理事件。您只需确保处理事件的控制器与触发事件的控制器共享 $scope。
当您触发 Angular 事件时,您可以使用 $emit 或 $broadcast。打电话
$scope.$emit(name, args);
将在作用域层次结构中向上发送事件,因此如果您有父控制器,它将听到该事件。 $broadcast 向下发送事件。但是,如果您的控制器都在同一层级注册,则必须使用 $rootScope.
无论您使用 $rootScope 还是 $scope,请确保将其注入正在侦听事件的控制器以及触发事件的控制器。
我正在开发一个用 AngularJS 编写的 Electron 应用程序。在 Electron 应用程序的主进程中,我正在监听 DownloadItem 事件。因此,每次用户下载文件时,都会触发该事件。在我的 Main.js 中,我有以下代码。
win.webContents.session.on('will-download', (event, item, webContents) => {
item.once('done', (event, state) => {
if (state === 'completed') {
win.webContents.send('download-message', 'completed', item.getSavePath());
} else if (state === 'interrupted') {
win.webContents.send('download-message', 'failed');
}
})
});
在 Angular 方面,我在 "main" 控制器(代表应用程序的起点)中等待这样的事件。所以,这里我有一些看起来像这样的代码:
const { ipcRenderer } = require('electron');
ipcRenderer.on('download-message', function (event, method, filepath) {
if (method === 'completed') {
// Do something interesting
} else if (method === 'failed') {
// Do something interesting
}
});
这工作得很好,但在主应用程序控制器中处理所有这些事件感觉有点难看。我想将它分离到它自己的控制器(例如 downloadController)。
我考虑过在它自己的服务(例如 downloadsService)中监听这个事件,但是因为我想操纵应用程序的视图(例如显示一些 success/failure 消息),我不认为这是该功能的合适位置。
所以,我正在寻找一种将此功能分离到特定控制器的好方法。
也许我只是不太了解 Angular 及其控制器的概念,所以任何建议都会很有帮助。
提前致谢!
您可以在用于修改视图的任何控制器中处理事件。您只需确保处理事件的控制器与触发事件的控制器共享 $scope。
当您触发 Angular 事件时,您可以使用 $emit 或 $broadcast。打电话
$scope.$emit(name, args);
将在作用域层次结构中向上发送事件,因此如果您有父控制器,它将听到该事件。 $broadcast 向下发送事件。但是,如果您的控制器都在同一层级注册,则必须使用 $rootScope.
无论您使用 $rootScope 还是 $scope,请确保将其注入正在侦听事件的控制器以及触发事件的控制器。