首頁  >  文章  >  web前端  >  AngularJS單選框及多選框實現雙向動態綁定_AngularJS

AngularJS單選框及多選框實現雙向動態綁定_AngularJS

WBOY
WBOY原創
2016-05-16 15:20:041377瀏覽

在AngularJS中提及雙向資料綁定,大家一定會想到ng-model指令。

一、ng-model

ng-model指令用來將input、select、textarea或自訂表單控制項同包含它們的作用域中的屬性進行綁定。它將目前作用域中運算表達式的值同給定的元素綁定。如果屬性不存在,它會隱式建立並將其新增至目前作用域。
總是用ng-model來綁定scope上一個資料模型內的屬性,而不是scope上的屬性,這可以避免在作用域或後代作用域中發生屬性覆蓋!

<input type="text" ng-model="modelName.somePrototype" />

二、type=”radio”

透過 value 屬性指定選取狀態下對應的值,並透過 ng-model 將單選框與 $scope 中的屬性對應,便實現了 type=”radio” 時的雙向動態綁定。

<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” 的雙向動態綁定。

<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" />篮球

四、完整範例

<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單選框及多選框實現雙向動態綁定的相關介紹,希望對大家的學習有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn