AngularJS学习之旅—AngularJS 表单(十六)

一、AngularJS 表单
  AngularJS 表单是输入控件的集合。
  HTML 控件
    以下 HTML input 元素被称为 HTML 控件:
    input 元素
    select 元素
    button 元素
    textarea 元素

  1、数据绑定

<input type="text" ng-model="firstname">   

    通过以上代码应用有了一个名为 firstname 的属性。

    它通过 ng-model 指令来绑定到你的应用。

    firstname 属性可以在 controller 中使用:

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.firstname = "John";
});

    也可以在应用的其他地方使用:

<form>
First Name: <input type="text" ng-model="firstname">
</form>
 
<h1>You entered: {{firstname}}</h1>

  

  2、Checkbox(复选框)

    checkbox 的值为 true 或 false,可以使用 ng-model 指令绑定,它的值可以用于应用中:

<form>
    Check to show a header:
    <input type="checkbox" ng-model="myVar">
</form>
 
<h1 ng-show="myVar">My Header</h1>

  3、单选框 

    我们可以使用 ng-model 来绑定单选按钮到你的应用中。

    单选框使用同一个 ng-model ,可以有不同的值,但只有被选中的单选按钮的值会被使用。

<form>
    选择一个选项:
    <input type="radio" ng-model="myVar" value="dogs">Dogs
    <input type="radio" ng-model="myVar" value="tuts">Tutorials
    <input type="radio" ng-model="myVar" value="cars">Cars
</form>

  4、下拉菜单

    使用 ng-model 指令可以将下拉菜单绑定到你的应用中。

    ng-model 属性的值为你在下拉菜单选中的选项:

<form>
选择一个选项:
<select ng-model="myVar">
    <option value="">
    <option value="dogs">Dogs
    <option value="tuts">Tutorials
    <option value="cars">Cars
</select>
</form>

  5、AngularJS 表单实例

<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    First Name:<br>
    <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" ng-model="user.lastName">
    <br><br>
    <button ng-click="reset()">RESET</button>
  </form>
  <p>form = {{user}}</p>
  <p>master = {{master}}</p>
</div>
 
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.master = {firstName: "John", lastName: "Doe"};
    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
});
</script>
原文地址:https://www.cnblogs.com/JamelAr/p/10362591.html