hlh3406 hlh3406 - 12 days ago 6
AngularJS Question

Angular calling a function from jquery/javascript - property undefined error

I'm trying to call an angular controller from my JavaScript. This is the first time I've used Angular for anything and I'm getting a bit lost!

I've followed this example:

http://dotnet-concept.com/Tips/2015/6/5798829/How-to-call-angularJS-function-from-javascript-jquery

But I'm getting this error:


Uncaught TypeError: Cannot read property 'TestAngularMethod' of
undefined(…)


Initially I had my own code in there, but I've stripped it all out to try and get this example to work first, but I'm not having any luck.

Can anyone see where I'm going wrong?

HTML

<div class="continueClass" id="divID" runat="server" ng-controller="TestController" ng-if="payment.type == 'PayPal' || payment.type == 'WorldPay'">
<asp:Button runat="server" Text="Continue" OnClick="Continue_Click"/>
</div>


ANGULAR

var myApp = angular.module('myApp', []);

myApp.controller('TestController', ["$scope", function ($scope) {
$scope.TestAngularMethod = function () {
alert('Hello you are calling angular js method.');
}
}]);


JavaScript

angular.element(document.getElementById('divID')).scope().TestAngularMethod();


I've looked at these without any luck at figuring out my own issue:

Call angularjs function using jquery/javascript

AngularJS. How to call controller function from outside of controller component

Call Angular Function with Jquery

Thanks!

Answer

Despite @Fissio is right ... you can try this code:

EDITED

JAVASCRIPT

var scope = angular.element('[id=divID]').scope();

if(scope ){ //check whether the div exist
    scope.TestController.TestAngularMethod(); //should execute your method
}
else{
    /* code if scope doesn't exist, div, probably removed because
    payment.type == 'PayPal' || payment.type == 'WorldPay' is probably false /*
}
Comments