从遗留代码中调用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中)
ExternalInterface.call("save", data);
将致电
window.save = function(data){
// want to update a service
// or dispatch an event here...
}
在JS调整大小功能中,我想发送一个控制器可以听到的事件。似乎创建服务是最佳选择。你能从AngularJS外部更新服务吗?控制器可以监听服务中的事件吗?在一个实验(点击小提琴)我做了似乎我可以访问服务但更新服务的数据未反映在视图中(在示例中,<选项>
应添加到< select>
)。
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 to 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.
从注射器中你可以获得任何服务在角度应用中。与范围类似,您可以调用已发布到它的任何方法。
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.
请记住,对范围内的角度模型或任何方法调用的任何更改都需要包装在 $ 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屋!