Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call angularjs function using jquery/javascript

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?

like image 899
MKB Avatar asked May 14 '14 07:05

MKB


People also ask

Which of the below command will help to call angularJS function using Javascript?

How to call angularJS function from javascript/jquery - Dot Net Concept. You can call your angularJS function from javascript or jquery with the help of angular. element().

How do you call a function in a scope?

Since both functions are in the same scope you can simply call $scope. fn1() inside fn2.


2 Answers

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

like image 104
Satpal Avatar answered Oct 18 '22 01:10

Satpal


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

like image 39
raman thakur Avatar answered Oct 18 '22 00:10

raman thakur