如何从外部访问组件Controller
How to access component Controller from outside
我正在使用 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 能够像这样访问控制器 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>
如何从外部获取对我的控制器的引用,以便我可以从常规 JavaScript(而非 Angular)使用它?
鉴于有 umleditor
组件,控制器实例可以通过以下方式检索:
angular.element(document.getElementById("editor")).controller('umleditor');
或者
angular.element(document.getElementById("editor")).isolateScope().$ctrl;
这被认为是一种不好的做法,应该用于测试或作为快速修复。通常必须做相反的事情,外部 JS 代码应该用 Angular app.
包裹起来
我正在使用 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 能够像这样访问控制器 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>
如何从外部获取对我的控制器的引用,以便我可以从常规 JavaScript(而非 Angular)使用它?
鉴于有 umleditor
组件,控制器实例可以通过以下方式检索:
angular.element(document.getElementById("editor")).controller('umleditor');
或者
angular.element(document.getElementById("editor")).isolateScope().$ctrl;
这被认为是一种不好的做法,应该用于测试或作为快速修复。通常必须做相反的事情,外部 JS 代码应该用 Angular app.
包裹起来