-1

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!

Community
  • 1
  • 1
hlh3406
  • 1,382
  • 5
  • 29
  • 46
  • 1
    Why do you need to do this anyway? You're generally not supposed to call a controller function from outside a controller, and there's likely a better solution available for whatever you're trying to do – Fissio Nov 21 '16 at 15:52
  • I have a legacy ajax call that appends to the page when it's succesful. I need to be able to check whether that id exists and then call an angular controller – hlh3406 Nov 21 '16 at 16:02
  • Why the down vote? – hlh3406 Nov 22 '16 at 08:33

1 Answers1

2

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 /*
}
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • Just realised it's not exactly the same: Uncaught TypeError: Cannot read property 'TestController' of undefined(…) – hlh3406 Nov 21 '16 at 16:15
  • Please, inspect the html in your web browser and verify that the div with `id="divID"` is there. Notice that if the condition `ng-if="payment.type == 'PayPal' || payment.type == 'WorldPay'"` is `false`, then the div is removed from the DOM, and you will probably get that error. See my answer edited. – lealceldeiro Nov 21 '16 at 16:26