Call AngularJS function using JavaScript

Call AngularJS function using JavaScript

Here you will see how to call AngularJS function using JavaScript also in this example we are passing one value to AngularJS function and set value in scope and return back to JavaScript function call finally show output using alert.

  • HTML Page:
<!DOCTYPE html>
<html data-ng-app="javaScript">
<head>
<meta charset="ISO-8859-1">
<title>Call AngularJS function using JavaScript</title>
<script
	src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script type="text/javascript">

	var serviceModule = angular.module('javaScript', []);
	
	serviceModule.controller('javaScriptController', function($scope) {

		$scope.javaScriptCallAngular = function(value) {
	        $scope.usersName = value;
	        return $scope.usersName;
	    };

	    $scope.javaScriptCallAngularJS = function(value) {
	        $scope.usersName = "Java Honk";
	    };
	
	});
	
	function javaScriptCall(value){
		var scope = angular.element(document.getElementById('idForJS')).scope();
		var retrunValue = scope.javaScriptCallAngular(value);
		alert (retrunValue);		
	}
	
</script>
</head>
<body id="idForJS" data-ng-controller="javaScriptController">


	<h2>Click below to get User Name:</h2>
	<div>
		<button onclick="javaScriptCall('Java Honk')">Get User name from JavaScript call to AngularJS</button>
		<button data-ng-click="javaScriptCallAngularJS()">Set User name AngularJS function call</button>

		<div>User Name: {{usersName}}</div>
	</div>

</body>
</html>
  • Output:

Call AngularJS function using JavaScript

 

Run this code in Plunker here

Leave a Reply

Your email address will not be published. Required fields are marked *