Call angularjs function using jquery/javascript

angularjs, javascript, jquery

Solution

Solution provide in the questions which you linked is correct. Problem with your implementation is that You have not specified the ID of element correctly.

Secondly you need to use `load` event to execute your code. Currently DOM is not loaded hence element is not found thus you are getting error.

HTML

<div id="YourElementId" ng-app='MyModule' ng-controller="MyController">
    Hi
</div>

JS Code

angular.module('MyModule', [])
    .controller('MyController', function ($scope) {
    $scope.myfunction = function (data) {
        alert("---" + data);
    };
});

window.onload = function () {
    angular.element(document.getElementById('YourElementId')).scope().myfunction('test');
}

DEMO

Problem

I am trying to call angular function using javascript/jQuery, following are the link I found - Call Angular Function with Jquery - Call controller function from outside of controller component I have taken the same steps but getting error in browser console ``` Uncaught TypeError: Cannot call method 'myfunction' of undefined ``` I have created the fiddle. How to call myfunction function and alert is displayed? Any Idea?

Original source

Related problems