How I can call function defined under controller from any place of web page (outside of controller component)?
It works perfectly when I press "get" button. But I need to call it from outside of div controller. The logic is: by default my div is hidden. Somewhere in navigation menu I press a button and it should show() my div and execute "get" function. How I can achieve this?
My web page is:
<div ng-controller="MyController"> <input type="text" ng-model="data.firstname" required> <input type='text' ng-model="data.lastname" required> <form ng-submit="update()"><input type="submit" value="update"></form> <form ng-submit="get()"><input type="submit" value="get"></form> </div>
My js:
function MyController($scope) { // default data and structure $scope.data = { "firstname" : "Nicolas", "lastname" : "Cage" }; $scope.get = function() { $.ajax({ url: "/php/get_data.php?", type: "POST", timeout: 10000, // 10 seconds for getting result, otherwise error. error:function() { alert("Temporary error. Please try again...");}, complete: function(){ $.unblockUI();}, beforeSend: function(){ $.blockUI()}, success: function(data){ json_answer = eval('(' + data + ')'); if (json_answer){ $scope.$apply(function () { $scope.data = json_answer; }); } } }); }; $scope.update = function() { $.ajax({ url: "/php/update_data.php?", type: "POST", data: $scope.data, timeout: 10000, // 10 seconds for getting result, otherwise error. error:function() { alert("Temporary error. Please try again...");}, complete: function(){ $.unblockUI();}, beforeSend: function(){ $.blockUI()}, success: function(data){ } }); }; }
If the two controller is nested in One controller. Then you can simply call: $scope. parentmethod();
You can't inject controllers into one another.
You can call your angularJS function from javascript or jquery with the help of angular. element().
Here is a way to call controller's function from outside of it:
angular.element(document.getElementById('yourControllerElementID')).scope().get();
where get()
is a function from your controller.
You can switch
document.getElementById('yourControllerElementID')`
to
$('#yourControllerElementID')
If you are using jQuery.
Also, if your function means changing anything on your View, you should call
angular.element(document.getElementById('yourControllerElementID')).scope().$apply();
to apply the changes.
One more thing, you should note is that scopes are initialized after the page is loaded, so calling methods from outside of scope should always be done after the page is loaded. Else you will not get to the scope at all.
UPDATE:
With the latest versions of angular, you should use
angular.element(document.getElementById('yourControllerElementID')).injector().get('$rootScope')
And yes, this is, in fact, a bad practice, but sometimes you just need things done quick and dirty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With