Home  >  Article  >  Web Front-end  >  How to Integrate AngularJS Controls with Legacy Code Requiring DOM Window Callbacks?

How to Integrate AngularJS Controls with Legacy Code Requiring DOM Window Callbacks?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 10:34:29122browse

How to Integrate AngularJS Controls with Legacy Code Requiring DOM Window Callbacks?

Call AngularJS from Legacy Code

Problem:
You need to integrate AngularJS controls with a legacy Flex application that requires callbacks attached to the DOM window.

Solution:

To dispatch events that AngularJS controllers can listen to from outside the framework, follow these steps:

  1. Get the Scope and Injector:

    • Use angular.element(domElement).scope() to obtain the current scope for the HTML element that is used to update the AngularJS application.
    • Use angular.element(domElement).injector() to access the current app injector.
  2. Obtain the AngularJS Service:

    • From the injector, obtain the AngularJS service that you wish to update.
  3. Invoke AngularJS Functions:

    • Within AngularJS, wrap any updates to the model or method invocations on the scope in $apply(function(){ ... }) to ensure proper change propagation.

Example Usage:

// Get the AngularJS scope and service
var scope = angular.element(document.getElementsByTagName('body')[0]).scope();
var service = scope.injector().get('myService');

// Invoke an AngularJS method
scope.$apply(function () {
  service.update();
});

Additional Notes:

  • Changes to the AngularJS model or scope method invocations must be wrapped in $apply().
  • You can use angular.element(domElement).controller() to access the AngularJS controller associated with the HTML element.

The above is the detailed content of How to Integrate AngularJS Controls with Legacy Code Requiring DOM Window Callbacks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn