从遗留代码调用 AngularJS [英] Call AngularJS from legacy code
问题描述
我正在使用 AngularJS 构建与旧版 Flex 应用程序交互的 HTML 控件.来自 Flex 应用程序的所有回调都必须附加到 DOM 窗口.
I'm using AngularJS to build HTML controls that interact with a legacy Flex application. All callbacks from the Flex app must be attached to the DOM window.
例如(在 AS3 中)
For example (in AS3)
ExternalInterface.call("save", data);
会打电话
window.save = function(data){
// want to update a service
// or dispatch an event here...
}
在 JS 调整大小函数中,我想发送一个控制器可以听到的事件.似乎创建服务是要走的路.您可以从 AngularJS 之外更新服务吗?控制器可以监听来自服务的事件吗?在一个实验(点击小提琴)中,我似乎可以访问服务但更新服务的数据不会反映在视图中(在示例中,应将 添加到
中).
From within the JS resize function I'd like to dispatch an event that a controller can hear. It seems that creating a service is the way to go. Can you update a service from outside of AngularJS? Can a controller listen for events from a service? In one experiment (click for fiddle) I did it seems like I can access a service but updating the service's data doesn't get reflected in the view (in the example an <option>
should be added to the <select>
).
谢谢!
推荐答案
从 angular 外部到 angular 的互操作与调试 angular 应用程序或与第三方库集成相同.
Interop from outside of angular to angular is same as debugging angular application or integrating with third party library.
对于任何 DOM 元素,您都可以这样做:
For any DOM element you can do this:
angular.element(domElement).scope()
获取元素的当前范围angular.element(domElement).injector()
获取当前应用注入器angular.element(domElement).controller()
获取ng-controller
实例.
angular.element(domElement).scope()
to get the current scope for the elementangular.element(domElement).injector()
to get the current app injectorangular.element(domElement).controller()
to get a hold of theng-controller
instance.
从注入器中,您可以获取 Angular 应用程序中的任何服务.同样,您可以从作用域调用任何已发布到它的方法.
From the injector you can get a hold of any service in angular application. Similarly from the scope you can invoke any methods which have been published to it.
请记住,对 Angular 模型的任何更改或作用域上的任何方法调用都需要包含在 $apply()
中,如下所示:
Keep in mind that any changes to the angular model or any method invocations on the scope need to be wrapped in $apply()
like this:
$scope.$apply(function(){
// perform any model changes or method invocations here on angular app.
});
这篇关于从遗留代码调用 AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!