<!-- 通用部分 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
......
<script src="//apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
......
</body>
</html>
數據源爲數組
1、ng-options創建(通過對象和數組循環輸出)(選項爲對象)
<div ng-app="xxApp" ng-controller="xxCtrl">
<select ng-model="selected" ng-options="x for x in TVnames">
</select>
</div>
<script>
var app = angular.module('xxApp', []);
app.controller('xxCtrl', function($scope) {
$scope.TVnames = ["《我在北京等你》", "《隱祕而偉大》", "《號手就位》"];
});
</script>
2、ng-repeat創建(通過數組循環 HTML 代碼輸出)(選項爲字符串)
<div ng-app="xxApp" ng-controller="xxCtrl">
<select>
<option ng-repeat="x in RoleNames">{{x}}</option>
</select>
</div>
<script>
var app = angular.module('xxApp', []);
app.controller('xxCtrl', function($scope) {
$scope.RoleNames = ["徐天", "顧耀東", "夏拙"];
});
</script>
ng-options VS ng-repeat
<div ng-app="xxApp" ng-controller="xxCtrl">
<p>選擇人物角色:</p>
<select ng-model="selected" ng-options="x.role for x in alls">
</select>
<p>角色: {{selected.role}}</p>
<p>劇名: {{selected.TV}}</p>
</div>
<script>
var app = angular.module('xxApp', []);
app.controller('xxCtrl', function($scope) {
$scope.alls = [
{role : "徐天", TV : "《我在北京等你》"},
{role : "顧耀東", TV : "《隱祕而偉大》"},
{role : "夏拙", TV : "《號手就位》"}
];
});
</script>
↑ ↓
<div ng-app="xxApp" ng-controller="xxCtrl">
<p>選擇人物角色:</p>
<select ng-model="selected">
<option ng-repeat="x in alls" value="{{x.TV}}">{{x.role}}</option>
</select>
<p>選擇: {{selected}}</p>
</div>
<script>
var app = angular.module('xxApp', []);
app.controller('xxCtrl', function($scope) {
$scope.alls = [
{role : "徐天", TV : "《我在北京等你》"},
{role : "顧耀東", TV : "《隱祕而偉大》"},
{role : "夏拙", TV : "《號手就位》"}
];
});
</script>
結論:當選項是對象時,獲取信息更多更靈活。因此,ng-options更具優勢!
數據源爲對象
(x,y)即(key,value)
選擇的值value可以是字符串,也可以是對象(由數據源決定)
<div ng-app="xxApp" ng-controller="xxCtrl">
<p>選擇人物角色:
<!-- (key,value) -->
<select ng-model="selected" ng-options="x for (x, y) in alls">
</select>
</p>
<!-- 選中的值y是字符串 -->
<p>選擇: {{selected}}</p>
</div>
<script>
var app = angular.module('xxApp', []);
app.controller('xxCtrl', function($scope) {
$scope.alls = {
role1 : "徐天",
role2 : "顧耀東",
role3 : "夏拙"
};
});
</script>
<div ng-app="xxApp" ng-controller="xxCtrl">
<!-- 一、下拉菜單使用key -->
<p>選擇人物角色:
<select ng-model="selected1" ng-options="x for (x, y) in alls">
</select>
</p>
<!-- 選中的值y是一個對象 -->
<p>選擇: {{selected1.role}}</p>
<p>劇名: {{selected1.TV}}</p>
<p>時間: {{selected1.time}}</p>
<br>
<!-- 二、下拉菜單直接使用對象的屬性 -->
<p>選擇劇名:
<select ng-model="selected2" ng-options="y.TV for (x, y) in alls">
</select>
</p>
<p>選擇: {{selected2.role}}</p>
<p>劇名: {{selected2.TV}}</p>
<p>時間: {{selected2.time}}</p>
</div>
<script>
var app = angular.module('xxApp', []);
app.controller('xxCtrl', function($scope) {
$scope.alls = {
role1 : {role : "徐天", TV : "《我在北京等你》", time : "2020年"},
role2 : {role : "顧耀東", TV : "《隱祕而偉大》", time : "2020年"},
role3 : {role : "夏拙", TV : "《號手就位》", time : "未知"}
}
});
</script>