AngularJS是當前非常的流行的前端框架,它的語法糖非常多,也極大的方便了前端開發者,但是有著用法還是需要去琢磨一下的。
ng-options
在select表單控件中,總結一下目前的幾種寫法。
普通寫法
<select> <option value="test1">test1</option> <option value="test1">test1</option> <option value="test1">test1</option> <option value="test1">test1</option></select>
優點:簡單
缺點:
使用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>優點:
缺點:
使用ng-options
這里使用一個年級、班級的選項來作為例子:即選擇年級之后再顯示對應的可選班級。
<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>注:
“請選擇"的option需要有value,不然會報錯
如果要設置默認選擇值,比如一開始就選擇"高一",則需要設置modal在數組里的對象。
$scope.modal.grade = $scope.modal.grades[2];//高一在數組的位置角標為2
優點:
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的用法同理。
以上所述是小編給大家介紹的ng-options和ng-checked在表單中的高級運用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答