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?
This question is related to
javascript
jquery
angularjs
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
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
Try this:
const scope = angular.element(document.getElementById('YourElementId')).scope();
scope.$apply(function(){
scope.myfunction('test');
});
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();
}
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", {_x000D_
controller: ["$window", function($window) {_x000D_
var self = this;_x000D_
_x000D_
self.logg = function() {_x000D_
console.log("logging!");_x000D_
};_x000D_
_x000D_
$window.angularControllerLogg = self.logg;_x000D_
}_x000D_
});_x000D_
_x000D_
window.angularControllerLogg();
_x000D_
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">
Source: Stackoverflow.com