在AngularJS中提及雙向資料綁定,大家一定會想到ng-model指令。
一、ng-model
ng-model指令用來將input、select、textarea或自訂表單控制項同包含它們的作用域中的屬性進行綁定。它將目前作用域中運算表達式的值同給定的元素綁定。如果屬性不存在,它會隱式建立並將其新增至目前作用域。
總是用ng-model來綁定scope上一個資料模型內的屬性,而不是scope上的屬性,這可以避免在作用域或後代作用域中發生屬性覆蓋!
1 | <input type= "text" ng-model= "modelName.somePrototype" />
|
登入後複製
二、type=”radio”
透過 value 屬性指定選取狀態下對應的值,並透過 ng-model 將單選框與 $scope 中的屬性對應,便實現了 type=”radio” 時的雙向動態綁定。
1 2 | <input type= "radio" name= "sex" value= "male" ng-model= "person.sex" />男
<input type= "radio" name= "sex" value= "female" ng-model= "person.sex" />女
|
登入後複製
三、type=”checkbox”
透過AngularJS 的內建指令ng-true-value 和ng-false-value ,指定多重選取框在選取和未選取狀態下對應的值,再透過ng-model 將其與$scope 中的屬性對應,便實現了type=”checkbox” 的雙向動態綁定。
1 2 3 | <input type= "checkbox" ng-true-value= "true" ng-false-value= "false" ng-model= "person.like.pingpong" />乒乓球
<input type= "checkbox" ng-true-value= "true" ng-false-value= "false" ng-model= "person.like.football" />足球
<input type= "checkbox" ng-true-value= "true" ng-false-value= "false" ng-model= "person.like.basketball" />篮球
|
登入後複製
四、完整範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <html ng-app= "myApp" >
<head>
<meta charset= "UTF-8" >
<title>radio & checkbox</title>
<script type= "text/javascript" src= "angular.js/1.4.4/angular.min.js" ></script>
</head>
<body>
<input type= "radio" name= "sex" value= "male" ng-model= "person.sex" />男
<input type= "radio" name= "sex" value= "female" ng-model= "person.sex" />女
<input type= "text" ng-model= "person.sex" />
<input type= "checkbox" ng-true-value= "true" ng-false-value= "false" ng-model= "person.like.pingpong" />乒乓球
<input type= "checkbox" ng-true-value= "true" ng-false-value= "false" ng-model= "person.like.football" />足球
<input type= "checkbox" ng-true-value= "true" ng-false-value= "false" ng-model= "person.like.basketball" />篮球
<span>{{ person.like.pingpong }} {{ person.like.football }} {{ person.like.basketball }} </span>
</body>
</html>
<script type= "text/javascript" >
var app = angular.module( 'myApp' , []);
app.run( function ( $rootScope ) {
$rootScope .person = {
sex: "female" ,
like: {
pingpong: true,
football: true,
basketball: false
}
};
});
</script>
|
登入後複製
以上就是關於AngularJS單選框及多選框實現雙向動態綁定的相關介紹,希望對大家的學習有所幫助。