復刻對象: KO範例2 - 下拉選單。
在NG,下拉選單(<select>)跟<input>一樣用ng-model="..."建立雙向繫結,如要透過繫結動態產生選項,可用ng-options Directive。ng-options的語法較特別,需穿插as for in等關鍵字,寫法又有好幾種,保哥有篇詳解可參考。若以物件陣列為資料來源,有兩種做法:
1) 繫結到物件本身: "選項文字 for 物件變數 in 選項物件陣列"
2) 分別擊結文字及值: "選項值 as 選項文字 for 物件變數 in 選項物件陣列"
其中物件變數是ng-options就地新增的變數名稱,不需要事先定義在ViewModel中。若採取第一種做法,ng-model="model.result"繫結的對象會是物件,而非<option value="…">的value,因此下方要寫成<span ng-bind="model.result.t">才會顯示選項文字,而changeToPhone()中,也是透過指定物件改變選取結果: self.result = self.options[2] 。
按鈕事件用ng-click指定要執行的JavaScript函式,記得要加上括號,寫成ng-click="model.changeToPhone()"。
程式範例如下: Live Demo
<!DOCTYPEhtml>
<htmlng-app="sampleApp">
<head>
<metacharset="utf-8">
<title>Lab 2 - 對應下拉選單</title>
</head>
<bodyng-controller="defaultCtrl">
<selectng-options="item.t for item in model.options"ng-model="model.result">
</select><br/>
<spanng-bind="model.result.v"></span><br/>
<inputtype="button"value="Set Phone"ng-click="model.changeToPhone()"/>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
<script>
angular.module("sampleApp", [])
.controller("defaultCtrl", function($scope) {
function myViewModel() {
var self = this;
self.options = [
{ t: "PC", v: "PC" },
{ t: "Notebook", v: "NB" },
{ t: "Phone", v: "Phone" }
];
self.result = self.options[0];
self.changeToPhone = function() {
self.result = self.options[2];
}
}
$scope.model = new myViewModel();
});
</script>
</body>
</html>
接著來看繫結選項文字及選項值的第二種做法: Live Demo
<bodyng-controller="defaultCtrl">
<selectng-options="item.v as item.t for item in model.options"ng-model="model.result">
</select><br/>
<spanng-bind="model.result"></span><br/>
<inputtype="button"value="Set Phone"ng-click="model.changeToPhone()"/>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
<script>
angular.module("sampleApp", [])
.controller("defaultCtrl", function($scope) {
function myViewModel() {
var self = this;
self.options = [
{ t: "PC", v: "PC" },
{ t: "Notebook", v: "NB" },
{ t: "Phone", v: "Phone" }
];
self.result = "NB";
self.changeToPhone = function() {
self.result = "Phone";
}
}
$scope.model = new myViewModel();
});
</script>
</body>
其中,ng-options被寫成"item.v as item.t for item in model.options",定義用item.v做為選項值,item.t做為選項文字。model.result的繫結對象也就變成了選項值,要指定result直接寫字串就好,例如: self.result = "Phone"。