AngularJS 學習筆記---AngularJS 模型(ng-model 指令)

AngularJS ng-model 指令


ng-model 指令用於綁定應用程序數據到 HTML 控制器(input, select, textarea)的值。php


ng-model 指令

ng-model 指令能夠將輸入域的值與 AngularJS 建立的變量綁定。css

AngularJS 實例

<div ng-app="myApp" ng-controller="myCtrl">
    名字: <input ng-model="name">
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name = "John Doe";
});
</script>html


嘗試一下 »html5


雙向綁定

雙向綁定,在修改輸入域的值時, AngularJS 屬性的值也將修改:瀏覽器

AngularJS 實例

<div ng-app="myApp" ng-controller="myCtrl">
    名字: <input ng-model="name">
    <h1>你輸入了: {{name}}</h1>
</div>app


嘗試一下 »ui


驗證用戶輸入

AngularJS 實例

<form ng-app="" name="myForm">
    Email:
    <input type="email" name="myAddress" ng-model="text">
    <span ng-show="myForm.myAddress.$error.email">不是一個合法的郵箱地址</span>
</form>spa


嘗試一下 »雙向綁定

以上實例中,提示信息會在 ng-show 屬性返回 true 的狀況下顯示。code

ps:

HTML 5 <input> type 屬性

定義和用法

type 屬性規定 input 元素的類型。

註釋:該屬性不是必需的,可是咱們認爲您應該始終使用它。

email 定義用於 e-mail 地址的文本字段

 

輸入類型 - email

email 輸入類型用於應該包含電郵地址的輸入字段。

當提交表單時,會自動地對 email 字段的值進行驗證。

實例

E-mail: <input type="email" name="user_email" />

親自試一試

提示:iPhone 的 Safari 瀏覽器會識別 email 輸入類型,而後改變觸摸屏的鍵盤來適應它(添加 @ 和 .com 選項)。

http://www.w3school.com.cn/html5/att_input_type.asp

BTW, 熟悉html5的人應該都知道,我是專門去查了一下,感受仍是很強大的,這在之前都是經過js去作的,html5已經實現了


應用狀態

ng-model 指令能夠爲應用數據提供狀態值(invalid, dirty, touched, error):

AngularJS 實例

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


嘗試一下 »


CSS 類

ng-model 指令基於它們的狀態爲 HTML 元素提供了 CSS 類:

AngularJS 實例

<style>

input.ng-invalid {
    background-color: lightblue;
}

</style>
<body>

<form ng-app="" name="myForm">
    輸入你的名字:
    <input name="myAddress" ng-model="text" required>
</form>


嘗試一下 »

ng-model 指令根據表單域的狀態添加/移除如下類:

  • ng-empty
  • ng-not-empty
  • ng-touched
  • ng-untouched
  • ng-valid
  • ng-invalid
  • ng-dirty
  • ng-pending
  • ng-pristine
相關文章
相關標籤/搜索