Directive ng-model AngularJS

ng-model The directive binds the value of HTML controls (input, select, textarea) to application data.

ng-model directive

Use ng-model Instructions, you can bind the value of the input field to variables created in AngularJS.

Esempio

<div ng-app="myApp" ng-controller="myCtrl">
  Name: <input ng-model="name">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.name = "Bill Gates";
});
</script>

Prova da solo

Two-way binding

Binding is two-way. If the user changes the value in the input field, the AngularJS property will also change its value:

Esempio

<div ng-app="myApp" ng-controller="myCtrl">
  Name: <input ng-model="name">
  <h1>You entered: {{name}}</h1>
</div>

Prova da solo

Validate user input

ng-model The instruction can provide type validation for application data (numbers, emails, required):

Esempio

<form ng-app="" name="myForm">
  Email:
  <input type="email" name="myAddress" ng-model="text">
  <span ng-show="myForm.myAddress.$error.email">Not a valid e-mail address</span>
</form>

Prova da solo

In the above example, only when ng-show The expression returned in the attribute true then the span will be displayed.

If ng-model If the property does not exist in the attribute, AngularJS will create one for you.

Application status

ng-model The instruction can provide the status of application data (valid, dirty, touched, error):

Esempio

<form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com'">
  Email:
  <input type="email" name="myAddress" ng-model="myText" required>
  <h1>Status</h1>
  {{myForm.myAddress.$valid}}
  {{myForm.myAddress.$dirty}}
  {{myForm.myAddress.$touched}}
</form>

Prova da solo

CSS class

ng-model The instruction provides CSS classes based on the state of HTML elements:

Esempio

<style>
input.ng-invalid {
  background-color: lightblue;
}
</style>
<body>
<form ng-app="" name="myForm">
  Inserisci il tuo nome:
  <input name="myName" ng-model="myText" required>
</form>

Prova da solo

ng-model Le direttive aggiungono o rimuovono le seguenti classi in base allo stato del campo del modulo:

  • ng-empty
  • ng-not-empty
  • ng-touched
  • ng-untouched
  • ng-valid
  • ng-invalid
  • ng-dirty
  • ng-pending
  • ng-pristine