Calling javascript/jquery function from angularJS and vice versa

Call angularJS function from javascript/jquery

With the help of angular.element(), You can call your angularJS function from JavaScript or Jquery.
In this article I will explain this with a simple short example and let’s see how it will work.

Angular Js Controller

Below is the simple angularJS controller where I have created a simple function which will show success alert.

ANGULAR JS CODE:


var app;

(function () {
app = angular.module("MyApp", []);
})();

app.controller('MyController', ["$scope", function ($scope) {
$scope.SuccessAlert = function () {
alert('Welcome to angular js method.');
}
}]);

HTML:

Copy below html code:

<div ng-app="MyApp" ng-controller="MyController" id="myCont">
	This is test div. Click the button to call javascript function 
	<span onclick="getSuccess()">Click Me</span>
</div>

JAVASCRIPT:
Copy below html code:

<script type="text/javascript">
	function getSuccess() {
		angular.element(document.getElementById('myCont')).scope().SuccessAlert();
	}
</script>

Call javascript/jquery function from angularJS.

You can simply call the JavaScript method in to Angular JS.
JAVASCRIPT CODE:


<script type="text/javascript">
    function ShowProgress() {
        alert("Upload In Progress");
    }
</script>

ANGULAR JS CODE:


app.controller("MyContl", function ($scope, angularService, $modal) {

    $scope.upload = function () {
        ShowProgress();
    }

});

Note: Use Angular directives to do DOM manipulation and you don’t require any jQuery code for DOM manipulation, Angular is sufficient for it.

Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkedin
Share On Pinterest

Be the first to comment

Leave a Reply

Your email address will not be published.

*


*