我有一个基于核心服务的 Angular 应用程序。
为了简化调试,我宁愿不必记住以下调用(来自 how to debug angular services in browser ):
tasks = angular.element(document.body).injector().get('tasks');
所以我的第一个想法是将此语句粘贴在我的index.html 中的脚本标记中,但如果我这样做,它会失败
Uncaught TypeError: Cannot read property 'get' of undefined
我一直在寻找 jQuery 文档的等效项,但似乎这不是 Angular 的方式。 Angular 方式似乎是这样的构造(来自 https://plus.google.com/+MicahGodbolt/posts/CiKyN2YUafM ):
angular.module('mushin', []).run(function() {
window.tasks = angular.element(document.body).injector().get('tasks');
})
但这给了我同样的错误。
将 Angular 服务放入 JavaScript 变量以在控制台中进行调试的正确方法是什么?
最佳答案
您可以在任何使用tasks
服务的地方将其附加到widow
对象。在上面使用 run()
方法的示例中,您只需将 tasks
服务添加为函数的依赖项,如下所示:
angular.module('mushin', []).run(function(tasks) {
window.tasks = tasks;
});
它现在失败了,因为在 run 方法的入口处,还没有任何东西绑定(bind)到 body 元素,所以你还没有注入(inject)器。
执行此操作的更“Angular 方式”是还依赖于 $window
服务,因此您的回调将变为:
angular.module('mushin', []).run(function($window, tasks) {
$window.tasks = tasks;
});
关于javascript - 如何为可以在控制台中检查的 Angular 服务创建变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25194839/