最典型的场景应该属于表单
类似表单和表格之类的场景,展示与提交一般是同时存在的。
通常情况下,单向数据绑定即可解决业务需求,如数据库的内容绑定到html中展示到页面即可
但若需要设计提交功能,双向数据绑定就会发生很便捷的作用。
双向数据绑定指的是:当文本框(或其他绑定标签、控件)发生改变时,Model也会随之发生改变
这样的话。已更改的model可以立即提交无需通过繁琐的jquery获取dom和value操作
<!doctype html> <html ng-app="UserInfoModule"> <head> <meta charset="utf-8"> <link href="https://cdn.bootcss.com/bootstrap/3.6.6/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="panel panel-primary"> <div class="panel-heading"> <div class="panel-title">双向数据绑定</div> </div> <div class="panel-body"> <div class="row"> <div class="col-md-12"> <form class="form-horizontal" role="form" ng-controller="UserInfoCtrl"> <div class="form-group"> <label class="col-md-2 control-label">邮箱:</label> <div class="col-md-10"> <input type="email" class="form-control" placeholder="推荐使用126邮箱" ng-model="userInfo.email"> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">密码:</label> <div class="col-md-10"> <input type="password" class="form-control" placeholder="只能是数字、字母、下划线" ng-model="userInfo.pwd"> </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">自动登录</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()">获取Form表单的值</button> <button class="btn btn-default" ng-click="setFormData()">设置Form表单的值</button> </div> </div> </form> </div> </div> </div> </div> <script src="https://cdn.bootcss.com/angular.js/1.5.0/angular.min.js"></script> <script type="text/javascript"> var UserInfoModule = angular.module(‘UserInfoModule‘, []); UserInfoModule.controller(‘UserInfoCtrl‘, ["$scope", function($scope) { $scope.userInfo = { email: "[email protected]", pwd: "123456", autoLogin: true } $scope.getFormData = function() { console.log($scope.userInfo); } $scope.setFormData = function() { $scope.userInfo = { email: "[email protected]", pwd: "123456123456123456123456", autoLogin: false } } }]) </script> </body> </html>
时间: 2024-10-27 11:54:18