48

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?

1

8 Answers 8

94

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

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

2 Comments

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..,.
How to do this if controller is the body..! I keep getting the error...! myfunction is not a function
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

3 Comments

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.
Nice. This led me to be able to call a method from a service/factory with the injector().get('servicename') method.
angular.element(document.getElementById('yourControllerElementID')).controller().scope().get(); can we write this code to call angular controller function?
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();

Comments

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">

2 Comments

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..,.
@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.
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

Comments

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();
}

Comments

0

Try this:

const scope = angular.element(document.getElementById('YourElementId')).scope();
scope.$apply(function(){
     scope.myfunction('test');
});

Comments

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();

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.