简体   繁体   中英

How to call an angularJS function from javascript?

I need to call an angularJS function from a javascript function. This is my javascript function:

function callAngularFunction(userid, serviceid, system) {

    angular.element(document.getElementById('myServiceId')).scope().test();

}

This is my controller code:

serviceApp.controller('myService', function ($scope,  $location, $window) {
    $scope.test = function () {
        console.log("hello from test");
    }
});

And this is how I included it in html :

<body ng-app="serviceApp" ng-controller="myService" id="myServiceId">

Whenever I call callAngularFunction , I get this error:

TypeError: Cannot read property 'test' of undefined

Check if you are importing the scripts in the end of the body tag </body> maybe for that reason it is not available in your code the id myServiceId

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