AngularJS ng-model instruktion

ng-model Instructions bind the value of HTML controls (input, select, textarea) to application data.

ng-model directive

Use ng-model Instructions allow you to bind the value of an input field to a variable created in AngularJS.

Eksempel

<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>

Prøv det selv

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:

Eksempel

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

Prøv det selv

Validate user input

ng-model Instructions can provide type validation for application data (numbers, email, required):

Eksempel

<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>

Prøv det selv

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

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

Application state

ng-model Instructions can provide the state of application data (valid, dirty, touched, error):

Eksempel

<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>

Prøv det selv

CSS class

ng-model Instructions provide CSS classes based on the state of HTML elements:

Eksempel

<style>
input.ng-invalid {
  background-color: lightblue;
}
</style>
<body>
<form ng-app="" name="myForm">
  Indtast dit navn:
  <input name="myName" ng-model="myText" required>
</form>

Prøv det selv

ng-model Instruktioner tilføjer/sletter følgende klasser baseret på status for formularkolonner:

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