In this article I will explain with an example, how to use ng-model directive in
AngularJS.
What is ng-model directive in AngularJS?
The
ng-model directive is used to bind the control’s (INPUT, SELECT and TEXTAREA) value to the
AngularJS variable.
HTML Markup
The following HTML Markup consists of:
DIV – For applying
ng-app and
ng-controller AngularJS directives.
TextBox – For displaying value.
The HTML TextBox has been assigned with an
AngularJS ng-model directive.
Button – For setting the value in TextBox.
The Button has been assigned with an
AngularJS ng-click directive.
<div ng-app="MyApp" ng-controller="MyController">
<input type="button" ng-click="SetTextBox()" value="Set TextBox">
<br />
<br />
<input type="text" ng-model="Greetings">
</div>
Setting TextBox value on Button Click using ng-model directive
When the Button is clicked, the SetTextBox function inside the Controller is called and it sets the Greetings Model variable.
The TextBox is bound with the
Greetings Model variable using the
ng-model AngularJS directive and hence when the
Greetings Model variable value is updated, the TextBox value will be updated and vice versa.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.SetTextBox = function () {
$scope.Greetings = "Hello Mudassar!";
}
});
</script>
Screenshot
Demo
Downloads