user3052526 February 2016

Call AngularJS method from Javascript

I am using AngularJS and Typescript. There is an external library that i am using and i need to call an AngularJS method from that library which is in vanilla javascript i followed this example

but sadly it did not work.

The error i get is that the function (which is in the my AngularJS class) is not a function.

  var scope = angular.element(
document.
getElementById("MainWrap")).
scope();
scope.$apply(function () {
    scope.createSession(data);
});

Now does this have to do with the vm that i use in typescript?

Following is the typescript code

module MyCtrl{

interface IMyController{
    createSession();
}

class MyController implements IMyController{

    constructor(
        ){

        var vm = this;


    }

    createSession(data){
             console.log(data);
    }
}

angular.module('app').controller('MyCtrl', MyController);

}

And here goes the HTML

<section id="MainWrap">

</section>

Any ideas?

Answers


Raulucco February 2016

scope is an object that Angular uses to bind the template and the controller. But you can use the syntax controllerAs to get rid of the scope and use the controller instance to bind the properties and methods of this, with the template. Once you do that the scope of the template will have a property named as the alias you gave to the controller either on the router/directive definition (controllerAs: alias), or the template ng-controller="MyCtrl as alias". This property is the controller instance thus you can call your method like that:

 var scope = angular.element(document.getElementById("MainWrap")).scope();
 scope.$apply(function () {
    scope.ctrlAlias.createSession(data);
 });

But if possible encapsulate this in a directive so you don't need to access the angular components from outside your application

Post Status

Asked in February 2016
Viewed 2,550 times
Voted 12
Answered 1 times

Search




Leave an answer