简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM