Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call AngularJS from legacy code

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.

For example (in AS3)

ExternalInterface.call("save", data); 

Will call

window.save = function(data){     // want to update a service      // or dispatch an event here... } 

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

Thanks!

like image 206
kreek Avatar asked May 07 '12 23:05

kreek


People also ask

Is AngularJS a legacy?

From its name, AngularJS, it is obvious that this is built on legacy JavaScript, which is among the top 3 programming languages even in 2022.

Is AngularJS still used in 2021?

In 2018, they announced that the major releases will be ceased after the release of AngularJS version 1.7. Currently it's under LONG TERM SUPPORT (LTS) period so, there will not be any kind of new major releases. The team of Angular JS totally focus on publishing patch releases, 1.7.

Why AngularJS is deprecated?

As of January 1, 2022, Google no longer updates AngularJS to fix security, browser compatibility, or jQuery issues. The Angular team recommends upgrading to Angular (v2+) as the best path forward, but they also provided some other options.


1 Answers

Interop from outside of angular to angular is same as debugging angular application or integrating with third party library.

For any DOM element you can do this:

  • angular.element(domElement).scope() to get the current scope for the element
  • angular.element(domElement).injector() to get the current app injector
  • angular.element(domElement).controller() to get a hold of the ng-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.

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. }); 
like image 110
Misko Hevery Avatar answered Nov 10 '22 11:11

Misko Hevery