ng-options和ng-checked在表單中的高級運用

AngularJS是當前很是的流行的前端框架,它的語法糖很是多,也極大的方便了前端開發者,可是有着用法仍是須要去琢磨一下的javascript

ng-options

在select表單控件中,總結一下目前的幾種寫法。html

普通寫法

<select>
    <option value="test1">test1</option>
    <option value="test1">test1</option>
    <option value="test1">test1</option>
    <option value="test1">test1</option>
</select>

優勢:簡單前端

缺點:java

  • 代碼很不簡潔,若是選項較多就會很亂
  • 不方便渲染,若是option在變須要使用js動態加載
  • 不方便存儲對象

使用ng-repeat

ng-repeat是angularJS中很是強大的一個directive,在渲染列表上極大的方便了前端開發者,那麼因爲有多個重複的option,固然可使用ng-repeat,用法以下:數組

<select>
    <option ng-repeat="option in options" value="{{option}}">{{option.name}}</option>
</select>
<script>
    $scope.options = [{id:1,name:'test1'},{id:2,name:'test2'},{id:3,name:'test3'}];
</scirpt>

優勢:前端框架

  • 代碼簡介
  • 可存儲對象,取值方便

缺點:框架

  • 沒有默認顯示!,在有些界面需求中,select多是須要placeholder同樣的顯示提示效果的,那麼使用這個方式顯示效果默認是空白
  • 沒法經過ng-model來獲取當前選擇的值

使用ng-options

這裏使用一個年級、班級的選項來做爲例子:即選擇年級以後再顯示對應的可選班級。spa

<select ng-model="modal.grade" ng-change="modalChangeGrade()" ng-options="grade.gradeText for grade in modal.grades">
   <option value="" disabled>請選擇</option>
</select>
<script>
    $scope.modal.grades = [
    {id:1,gradeText:'初一',classes:[]},
    {id:2,gradeText:'初二',classes:[]},
    {id:3,gradeText:'高一'},classes:[]];
    $scope.modalChangeGrade = function(){
        //班級的HTML片斷就不在這裏寫了
        $scope.modal.classes = $scope.modal.grade.classes;
    }
</scirpt>

注:code

  • 「請選擇"的option須要有value,否則會報錯
  • 若是要設置默認選擇值,好比一開始就選擇"高一",則須要設置modal在數組裏的對象。
$scope.modal.grade = $scope.modal.grades[2];//高一在數組的位置角標爲2

優勢:htm

  • 代碼簡潔,易於維護
  • 有默認顯示
  • 可使用ng-modal準確獲取當前選擇的對象

ng-checked

checkbox和radio是咱們常常使用到的表單組件,那麼如何使用angularJs簡潔方便的獲取當前已選擇對象呢?

這裏只說angularJs的用法:

下面依然以年級和班級爲例:

<div ng-repeat="class in grade.classes" ng-click="class.is_checked=!class.is_checked">
   <input type="checkbox" value="" ng-checked="class.is_checked">
   {{class.id+'班'}}
</div>

最後須要查看有哪些checkbox被選中時,只須要遍歷$scope.grade.classes數組查看有哪些對象的is_checked屬性爲true便可。

radio的用法同理。

相關文章
相關標籤/搜索