Call Angularjs from Legacy Code

Call AngularJS from legacy code

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

Broadcast from legacy code to Angular via rootScope

It seems that angular.injector() is creating new module instance and
it is independent from the module instance bound with the html via ng-app attribute.

So solution is to use manual bootstrap and obtain the injector there.
Use this injector you can access the service instance and $rootScope which
is actually controlling the view.

Here is the updated fiddle; http://jsfiddle.net/d8vX3/1/

AngularJS register events from legacy library

Like this way:

function MyController($scope, $window){

$window.thridpartyLibrary.on('somethingHappend', function(evt){
$scope.$apply(function(){
$scope.myVariable = evt;
});
});
}

E.g.: with $scope.$apply you can let your angular context be aware of the event that is triggered from another library.

Passing a JS-Class to AngularJS(1.4.x) service to use its variables and functions

A problem in your original setup is when you register your class as a service, you're not returning the instance of the class:

function(){new DummyClass()}

Should be:

function(){return new DummyClass()}

Autoreturning only works when you don't use curly braces, like

() => new DummyClass()

Call angular js method by silverlight control

You can try writing your custom Javascript code and do something like this

<script type="text/javascript">
function callAngularFunc(message) {
angular.element($("#elementID")).scope().testMethodForSilverlight(message);
}
</script>

Here, elementID will be the DOM element that the angular controller is bound to.

There is more info related accessing angular data from outside in this post.

Then, in your silverlight code, make the call like this

public class ViewModel : ViewModelBase, INotifyDataErrorInfo
{
public void CallAngularMethod()
{
HtmlPage.Window.Invoke("callAngularFunc", new[] { "Testing" });
}
}


Related Topics



Leave a reply



Submit