47

I am trying to call angular function using javascript/jQuery, following are the link I found

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?

Community
  • 1
  • 1
MKB
  • 7,587
  • 9
  • 45
  • 71

8 Answers8

93

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

Satpal
  • 132,252
  • 13
  • 159
  • 168
  • I forgot to add id in fiddle, sorry for that. And you are absolutely right, problem is with my code run before DOM load. Your code works great. Thanks..,. – MKB May 14 '14 at 08:05
  • How to do this if controller is the body..! I keep getting the error...! myfunction is not a function – gayan1991 Aug 08 '15 at 09:42
35

You can use following:

angular.element(domElement).scope() to get the current scope for the element

angular.element(domElement).injector() to get the current app injector

angular.element(domElement).controller() to get a hold of the ng-controller instance.

Hope that might help

Arnab Nandy
  • 6,472
  • 5
  • 44
  • 50
raman thakur
  • 359
  • 3
  • 3
  • If I could add more than +1 for this, I would. The third one is the best one here, because I'm not using the $scope which allows me to decouple my code from angular v1. – Adam Levitt Apr 01 '15 at 16:42
  • Nice. This led me to be able to call a method from a service/factory with the injector().get('servicename') method. – kukabuka Jul 16 '15 at 22:52
  • `angular.element(document.getElementById('yourControllerElementID')).controller().scope().get();` can we write this code to call angular controller function? – Thomas Nov 05 '15 at 18:29
10

Another way is to create functions in global scope. This was necessary for me since it wasn't possible in Angular 1.5 to reach a component's scope.

Example:

angular.module("app", []).component("component", {
  controller: ["$window", function($window) {
    var self = this;
    
    self.logg = function() {
      console.log("logging!");
    };
    
    $window.angularControllerLogg = self.logg;
  }
});
               
window.angularControllerLogg();
Carl Emmoth
  • 473
  • 4
  • 11
7

Your plunker is firing off

angular.element(document.getElementById('MyController')).scope().myfunction('test');

Before anything is rendered.

You can verify that by wrapping it in a timeout

setTimeout(function() {
   angular.element(document.getElementById('MyController')).scope().myfunction('test');    
}, 1000);

You also need to acutally add an ID to your div.

<div ng-app='MyModule' ng-controller="MyController" id="MyController">
ivarni
  • 17,658
  • 17
  • 76
  • 92
  • I forgot to add id in fiddle, sorry for that. And you are absolutely right, problem is with my code run before DOM load. Thanks..,. – MKB May 14 '14 at 08:02
  • @MdAslam I haven't used angular for anything for 3 years so I'd suggest trying to ask a new question if there's none about doing that already. The only option I can think of is to expose it via the global window object but there might be better ways. – ivarni Sep 25 '18 at 13:36
2

One doesn't need to give id for the controller. It can simply called as following

angular.element(document.querySelector('[ng-controller="HeaderCtrl"]')).scope().myFunc()

Here HeaderCtrl is the controller name defined in your JS

madhu131313
  • 7,003
  • 7
  • 40
  • 53
1

Please check this answer

// In angularJS script
$scope.foo = function() {
    console.log('test');
};
$window.angFoo = function() {
    $scope.foo();
    $scope.$apply(); 
};
    
// In jQuery
if (window.angFoo) {
    window.angFoo();
}
Joundill
  • 6,828
  • 12
  • 36
  • 50
Adeel Gill
  • 353
  • 4
  • 19
0

Try this:

const scope = angular.element(document.getElementById('YourElementId')).scope();
scope.$apply(function(){
     scope.myfunction('test');
});
Mahdi P.
  • 167
  • 1
  • 5
0

There is a simple way to do that, by creating a hidden element inside your scope (with a ID or css class, up to you), and via javascript you find the element and trigger the click.

Hidden div example:

<div class="whatever-class-you-want" id="whatever-unique-id" ng-click="callAngularFunctionThatYouWant()">
</div>

Call you scoped function:

document.getElementsByClassName('whatever-class-you-want')[0].click();

or

document.getElementById('whatever-unique-id').click();
Federico Fusco
  • 545
  • 1
  • 5
  • 18