【问题标题】:Simulate click on angular element模拟点击角度元素
【发布时间】:2019-06-28 02:58:07
【问题描述】:

我需要从应用程序外部调用一些 Angular 控制器函数。我无法修改 Angular 应用程序本身 - 为简单起见,代码应该在浏览器控制台中运行(最终将集成在 Chrome 扩展程序中)。

我查看了其他答案 - 但它们已经过时或根本不起作用。 AngularJS. How to call controller function from outside of controller component 看起来很有希望,但无法让它发挥作用。

给定以下 HTML:

<div data-ng-if="::ctrl.isEntityNotesEnabled"
     data-ng-class="{'menu__item--enabled': ctrl.isNotesShown}"
     data-ng-click="ctrl.toggleNotesSection()" role="button">
  Show 
</div>

我想从 JavaScript 调用 ctrl.toggleNotesSection() - 但在应用程序之外。

更新:我尝试过的一些事情:

// this will return undefined, old AngularJS approach
angular.element('ng-controller-selector').scope()
// seems a bit closer to what I want, but "ctrl" isn't exposed, nor toggleNotesSection()
angular.element('ng-controller-selector').injector().get('$rootScope')
// I also tried using the DIV element, without success
angular.element('div selector')

【问题讨论】:

  • 如果您无法修改应用程序以放入适当的侦听器,则链接的答案几乎是唯一可行的方法。看到这里得到相同的答案:stackoverflow.com/questions/22795628/…
  • @samnupel 这样的东西可以工作,但需要修改 Angular 应用程序。
  • @bryan60 - 这似乎适用于旧版本的 Angular,无法正常工作 - 你有示例代码吗?
  • @samnupel - 抱歉,我正在查看公认的解决方案和其他解决方案,无法弄清楚。此外,可以从外部“连接”到角度。在我的代码的另一部分,我正在这样做:const injector = angular.element(document.body).injector(), someService = injector.get("someService"); someService.update(data); 所以我觉得我已经接近解决方案了......

标签: javascript angularjs


【解决方案1】:

我尝试过的一些事情:

// this will return undefined, old AngularJS approach
angular.element('ng-controller-selector').scope()

AngularJS 的生产版本禁用了.scope() 方法以提高性能。

如果您希望使用此信息调试应用程序,则应在浏览器中打开调试控制台,然后直接在此控制台中调用此方法:

angular.reloadWithDebugInfo();

页面应该重新加载并且调试信息现在应该可用了。

有关更多信息,请参阅 $compileProvider 和 angular.reloadWithDebugInfo 上的文档页面。

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 2016-11-01
    • 2015-03-03
    • 2014-07-26
    • 2017-04-05
    • 2021-01-07
    • 2017-02-26
    • 1970-01-01
    相关资源
    最近更新 更多