菜鸟笔记-AngularJS 6月1日学习(表单)

AngularJS 表单
HTML 控件
以下 HTML input 元素被称为 HTML 控件:
input 元素
select 元素
button 元素
textarea 元素
Input 控件使用 ng-model 指令来实现数据绑定。
<input type="text" ng-model="firstname">
firstname 属性可以在 controller 中使用:
app.controller('formCtrl', function($scope) { $scope.firstname = "John"; });
也可以在应用的其他地方使用:
<h1>You entered: {{firstname}}</h1>
Checkbox(复选框)
checkbox 的值为 true 或 false,可以使用 ng-model 指令绑定,它的值可以用于应用中:
<input type="checkbox" ng-model="myVar">
<h1 ng-show="myVar">My Header</h1>
个人理解: 用ng-model绑定到复选框,当选中的时候 myVar=true
ng-show绑定到h1  当myVar为真的时候,ng=show为真,既显示


单选框
单选框使用同一个 ng-model ,可以有不同的值,但只有被选中的单选按钮的值会被使用。
  选择一个选项:
 <input type="radio" ng-model="myVar" value="dogs">Dogs
<div ng-switch="myVar">
  <div ng-switch-when="dogs">
     <h1>Dogs</h1>
  </div>
</div>
ng-model绑定到单选框时候 被选中到的值为dogs
ng-switch进行判断 
ng-switch-when进行筛选 当选中值为dos 时候显示 里面的内容
ng-switch 指令根据筛选结果显示或隐藏 HTML 区域。
下拉菜单
ng-model 属性的值为你在下拉菜单选中的选项:
  选择一个选项:
<select ng-model="myVar"> <option value="dogs">Dogs  </select>
<div ng-switch="myVar"><div ng-switch-when="dogs">
     <h1>Dogs</h1>
  </div></div>
HTML 表单
<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>
Note novalidate 属性是在 HTML5 中新增的。禁用了使用浏览器的默认验证。
实例解析
ng-app 指令定义了 AngularJS 应用。
ng-controller 指令定义了应用控制器。
ng-model 指令绑定了两个 input 元素到模型的 user 对象。
formCtrl 函数设置了 master 对象的初始值,并定义了 reset() 方法。
reset() 方法设置了 user 对象等于 master 对象。
ng-click 指令调用了 reset() 方法,且在点击按钮时调用。
novalidate 属性在应用中不是必须的,但是你需要在 AngularJS 表单中使用,用于重写标准的 HTML5 验证。
个人理解:
因为绑定了两个 input 元素到模型的 user 对象。
所以input元素改变,也就改变了form元素
而master给user的不是对象传递而是值传递,所以master不会改变
下拉框初始化无默认值,或者有空白选项,影响美观,可通过以下方法调整:
 1.给定初始化信息(ng-init)
 2.隐藏空白选项(ng-show="false")
<form>
  选择一个选项:
  <select ng-model="myVar" ng-init="myVar='tuts'">
    <option ng-show="false" value="">
  </select>
</form>

猜你喜欢

转载自blog.csdn.net/qq_25744257/article/details/80539376