angularjs的数据绑定方式有2种。一种是从数据绑定到视图另一种是从视图中用户的输入’绑定到‘数据’
方式一:从数据绑定到视图
①常用指令: ngRepeat/ngIf/ngShow…
②双花括号:{{}}
方式二:从‘视图中用户的输入’绑定到‘数据’
绑定方式:指令:ngModel
如果要监听数据的变化:
$scope.$watch('txt',function(){
})
下面是一个很好的数据绑定案例:
`<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="js/angular.js"></script>
</head>
<body>
<div ng-controller="myCtrl">
<!-- 方向2的绑定:通过ngModel将用户的输入绑定到了数据-->
请输入留言内容:
<textarea ng-model="userMsg"></textarea>
<br/>
选择所在的城市:
<!--<select ng-model="loc">
<option value="bj">北京</option>
<option value="sh">上海</option>
<option value="gz">广州</option>
</select>-->
<select
ng-model="city"
ng-options="city.cityName for city in cities">
</select>
<br/>
选择性别:
<input type="radio"
ng-model="userSex"
name="sex" value="male"/>男
<input type="radio"
ng-model="userSex"
name="sex" value="female"/>女
<br/>
是否同意 <input type="checkbox" ng-model="userIsAgree"/>
</div>
<script>
var app = angular.module('myApp', ['ng']);
app.controller('myCtrl', function ($scope) {
$scope.userMsg = "";
$scope.loc = 'bj';
$scope.userSex = 'male';
$scope.userIsAgree = true;
// 模拟一个城市列表,准备显示在下拉菜单中
$scope.cities = [
{cityName:'北京',cityValue:'bj'},
{cityName:'上海',cityValue:'sh'},
{cityName:'广州',cityValue:'gz'},
]
$scope.city = $scope.cities[1];
//可以通过$watch去监听模型数据的变化
$scope.$watch('userMsg', function () {
console.log($scope.userMsg);
})
$scope.$watch('city', function () {
console.log($scope.city);
})
$scope.$watch('userSex', function () {
console.log($scope.userSex);
})
$scope.$watch('userIsAgree', function () {
console.log($scope.userIsAgree);
})
});
</script>
</body>
</html>`