Search code examples
javascriptangularjsangularjs-components

How to access component Controller from outside


I'm using Angular 1.5 and I have a component like this

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

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

Then in app/uml-editor/umleditor.html I would like to have some javascript able to access the controller UmlEditorController like this:

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

How do I get a reference to my Controller from outside so that I can use it from regular JavaScript (not Angular)?


Solution

  • Given there is umleditor component, controller instance can be retrieved with:

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

    Or

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

    This is considered a bad practice and should be used in testing or as a quick fix. Generally the opposite thing has to be done, external JS code should be wrapped with Angular app.