1. 程式人生 > >AngularJS單選框及多選框實現雙向動態繫結

AngularJS單選框及多選框實現雙向動態繫結

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

一、ng-model

ng-model指令用來將input、select、textarea或自定義表單控制元件同包含它們的作用域中的屬性進行繫結。它將當前作用域中運算表示式的值同給定的元素進行繫結。如果屬性不存在,它會隱式建立並將其新增到當前作用域中。
始終用ng-model來繫結scopescope上的屬性,這可以避免在作用域或後代作用域中發生屬性覆蓋!

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

四、完整示例

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>radio & checkbox</title>
    <script type="text/javascript" src="http://cdn.bootcss.com/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>