In this article I will explain with an example, how to get HTML Form Input value inside Controller on Button click in AngularJS.
Inside the Controller, the Button has been assigned ng-click directive and value of the TextBox will be fetched using the $scope function inside Controller in AngularJS.
How to get HTML Form Input value inside Controller on Button click in AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML TextBox and a Button to which ng-click attribute has been assigned.
When the Button is clicked, the ShowAlert function of the Controller gets called, which displays the value of Name TextBox using JavaScript Alert message box.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.ShowAlert = function () {
if (typeof ($scope.Name) == "undefined" || $scope.Name == "") {
$window.alert("Please enter your name!");
return;
}
$window.alert("Hello " + $scope.Name);
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
Name:
<input type="text" ng-model="Name" />
<br />
<br />
<input type="button" value="Show Alert" ng-click="ShowAlert()" />
</div>
</body>
</html>
Screenshot
Demo
Downloads