2016年7月26日 星期二

AngularJs Select Binding

AngularJs 綁定 Select Element 的方法有二種, 一種為使用 ngOptions 另一種為 ngRepeat
使用 ngOptions 的方法如下


nOptions 會自動產生 <option></option> 並綁定 data.availableOptions 的 item
其中 option.name 為選單的 Text, option.id 為 Value
data.selectedOption 則為 data.availableOptions 的一個 item, 也就是當 selected 事件產生時 data.selectedOption = { id: x, name: yyyy }

使用 ngRepeat 的方法如下


ngRepeat 如同一般的用法在 <option> 中加入 ng-repeat Directive , 當 selected 事件產生時 data.model = option.id 而不是整個 data.availableOptions item
若要設定 selected 可以用 ng-selected directive
<option ng-selected="option.id == data.model">

二種用法的差別如下
ngOptions:
1.option element 自動產生
2.ng-model 為 object
3.有使用 track by 條件要注意 track by 值不能重複
4.指定 ng-model 即可 selected option

ngRepeat:
1.手動填入 ng-repeat option.name, option.id 到 Text 及 Value  
2.ng-model 為 value
3.需使用 ng-selected 才能 selected option

官方文件參考 Angular JS API Select

沒有留言:

張貼留言