咱們在頁面中加入一個表單:
javascript
<span style="font-size:10px;"><!DOCTYPE html> <html ng-app="userInfoModule"> <head> <meta name="content-type" content="text/html; charset=UTF-8"> <script src="angular-1.5.0/angular.min.js"></script> <script src="js/Forms.js"></script> <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"> <script> </script> </head> <body> <div class="panel panel-primary"> <div class="panel-heading"> <div class="panel-title"> Two-way Binding demo </div> </div> <div class="panle-body"> <div class="row"> <div class="col-md-12"> <form class="form-horizontal" role="form" ng-controller="userInfoControl"> <div class="form-group"> <label class="col-md-2 control-label"> email-address: </label> <div class="col-md-10"> <input type="email" class="form-control" placeholder="please input you email-address" ng-model="userInfo.email"> </div> </div> <div class="from-group"> <label class="col-md-2 control-label"> password: </label> <div class="col-md-10"> <input type="password" class="form-control" placeholder="please input your password" ng-model="userInfo.password"> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <div class="checkbox"> <label > <input type="checkbox" ng-model="userInfo.autoLogin">login auto </label> </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button class="btn btn-default" ng-click="getFormData()"> get form data </button> <button class="btn btn-default" ng-click="setFormData()"> set form data </button> <button class="btn btn-default" ng-click="resetFormData()"> reset form data </button> </div> </div> </form> </div> </div> </div> </div> </body> </html> </span>
以後,定義模塊跟controller,並在controller中綁定咱們的model跟事件。css
var userInfoModule=angular.module('userInfoModule',[]); /*定義模塊*/ userInfoModule.controller('userInfoControl',['$scope',function($scope){/*定義Controller,並注入對象*/ $scope.userInfo={ /*初始化數據*/ email:"liuhuichao1128@163.com", password:"1112345", autoLogin:true }; $scope.getFormData=function(){ /*獲取模型數據*/ console.log($scope.userInfo); }; $scope.setFormData=function(){/*設置數據*/ $scope.userInfo={ email:"2523579001@163.com", password:"000000000000", autoLogin:true }; }; $scope.resetFormData=function(){/*重置數據*/ $scope.userInfo={ email:"liuhuichao1128@163.com", password:"1112345", autoLogin:true }; }; }]);
代碼解析:
用完以後,最大的感受就是,DOM操做少了,數據雙向綁定後,頁面上表單改變值,也不用再從新取值,很是方便。html