1

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

4
  • looks like you do not have an HTML element with ID myServiceId in the DOM. To check it just execute document.getElementById('myServiceId') in your debugger console. It should print undefined if the element is not found. Commented Jun 21, 2020 at 12:10
  • @Andriy it can be possible cause the above code is deployed in server and I'm calling the function named callAngularFunction from my localhost project. But i'm new and have no idea how to proceed from here Commented Jun 21, 2020 at 12:30
  • try to inspect your available HTML code in debugger -> elements and try to find closest to your component element with unique CSS selector (w3schools.com/cssref/css_selectors.asp) (id, unique class or property) and then try to select it with documnet.querySelector() (instead of document.getElementById()) Commented Jun 21, 2020 at 14:43
  • Looking at your previous question, this appears to be an XY problem. Your are trying to solve the previous problem on your own using a method that won't work. Thus obscuring the actual problem. Commented Jun 21, 2020 at 15:26

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.