Please enable Javascript for better experience...
How to call angularJS function from javascript/jquery
By Rahul Kumar Jha | Jun 26, 2015 | In Tips | Update: Jun 29, 2015 | Total Views [ 42051 ]
(8 Like)
Rate

You can call your angularJS function from javascript or jquery with the help of angular.element(). In this article I will explain this with a simple short example.

Introduction

Many time it may happens that you need to call a method created in angularJS in javascrip/jquery function block. One scenario can be that you are using angularJS in your MVC application and you are making an ajax call and OnSuccess() event you need to call an angularJS method into your javascript code block. Don't go on my words. It is not so tough as I am trying to make it. You can do this using one line of code calling angularJS scope into your javascript block. Let's see how can we do this with a short example.

Angular JS Controller

Below is the simple angularJS controller where I have created a simple function which will open an alert box.

var app;

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

app.controller('TestController', ["$scope", function ($scope) {
    $scope.TestAngularMethod = function () {
        alert('Hello you are calling angular js method.');
    }
}]);

HTML

Copy below html code.

        <div class="margin-bottom width100floatleft" ng-app="TestApp" ng-controller="TestController" id="divID">
            This is test div. Click the button to call javascript function
        <span style="border:1px solid black; border-radius:5px; padding:10px;" onclick="OnSuccessData()">Click Me</span>
        </div>

Javascript

Copy below javascript code.

    <script type="text/javascript">
        function OnSuccessData() {
            angular.element(document.getElementById('divID')).scope().TestAngularMethod();
        }
    </script>

If you noticed in javascript code, I am using angularJS scope of TestController and calling TestAngularMethod() from here. This line will allow you to use your angularJS controller scope into javascript also. This was the simple trick I used to call angularJS function into my javascript function. Hope it can help you.

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer dotnet-concept.com

Public profile: user/profile/99900001


Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments


 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment
 
 
 
 
 
 
Sponsors