javascript - 如何从外部访问组件Controller

标签 javascript angularjs angularjs-components

我使用的是 Angular 1.5,我有一个这样的组件

        angular
        .module('appliactionModule')
        .component('umleditor', {
            bindings: {
                 ...
            },
            templateUrl: 'app/uml-editor/umleditor.html',
            controller: UmlEditorController
        });

       function UmlEditorController( ... ){ ... };

然后在 app/uml-editor/umleditor.html 中,我希望有一些 javascript 能够像这样访问 Controller UmlEditorController:

<div class="editor-wrapper" id="editor">
  ...
  <script>
     // Accessing Services like this works
     var FooService = angular.element('*[ng-app]').injector().get("FooService");

     // How do I get the controller?
      controller.doSomething();

  </script>
</div>

如何从外部获取对我的 Controller 的引用,以便我可以从常规 JavaScript(而非 Angular)中使用它?

最佳答案

如果有 umleditor 组件, Controller 实例可以通过以下方式检索:

angular.element(document.getElementById("editor")).controller('umleditor');

或者

angular.element(document.getElementById("editor")).isolateScope().$ctrl;

这被认为是一种不好的做法,应该用于测试或作为快速修复。通常必须做相反的事情,外部 JS 代码应该用 Angular 应用程序包装。

关于javascript - 如何从外部访问组件Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45263908/

相关文章:

javascript - 在 Angular js 中使用 ng-repeat 指令在表中显示数组数据

angularjs - ngMock 将 $scope local 注入(inject) Controller

javascript - 在 Angular 1.5 组件中使用 ControllerAs

Visual Studio 2010 速成版的 Javascript 插件

javascript - 如何在 TypeScript 中为 Node 使用无类型的 JS NPM 模块?

javascript - 如何使表单字段有条件为必填

angularjs:从指令广播到 Controller

javascript - 如何在 AngularJS 1.x 中将数据从组件发送到父级

javascript - 错误 : incompatible types: MainActivity cannot be converted to FragmentActivity . 添加包(新 ReactDatePackage(本))

javascript - 如何在 perl 中执行页面的 javascript 函数?