AngularJs ng-options

前端之家收集整理的这篇文章主要介绍了AngularJs ng-options前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1. select标签中的ng-model 使用时注意,选择的结果

<form class="form-horizontal container" ng-app="myApp" ng-controller="validateCtrl"
        name="myForm" novalidate>
    <div class="form-group">
        <label class="control-label">地区:</label>
        <!--如果不指定x.id,ng-model选择的结果是object对象-->
        <select ng-model="areaID" ng-options="x.name for x in items"></select>
        <span class="text-danger" ng-show="myForm.areaID.$dirty && myForm.areaID.$invalid">
            <span ng-show="myForm.areaID.$error.required">地区是必须的</span>
        </span>
    </div>
</form>

    var app = angular.module('myApp',[]);
    app.controller('validateCtrl',function ($scope,$timeout) {
        $scope.items = [
            { id: 1,name: '山东' },{ id: 2,name: '山西' }
        ];
        $scope.areaID = 1;
        $scope.$watch('areaID',function (newValue) {
            console.info(newValue);
        });
    });

选择的结果是:object


<div class="form-group">
    <label class="control-label">地区:</label>
    <!-- x.id as x.name 用来指定选择结果为ID,显示的是name  --> 
    <select ng-model="areaID" ng-options="x.id as x.name for x in items"></select>
    <span class="text-danger" ng-show="myForm.areaID.$dirty && myForm.areaID.$invalid">
        <span ng-show="myForm.areaID.$error.required">地区是必须的</span>
    </span>
</div>
选择的结果是ID


2.使用group by分组显示

<form class="form-horizontal container" ng-app="myApp" ng-controller="validateCtrl"
        name="myForm" novalidate>
    <div class="form-group">
        <label class="control-label">动物:</label>
        <!--使用group by 可以分组显示-->
        <select ng-model="AniID" ng-options="x.id as x.name group by x.sex for x  in animals"></select>
    </div>
</form>
    var app = angular.module('myApp',$timeout) {
        $scope.animals = [
          {
              id: '00001',name: '猫',sex: '雌',food: '鱼',favor: '玩球'
          },{
              id: '00002',name: '狗',sex: '雄',food: '骨头',favor: '接盘子'
          },{
              id: '00003',name: '兔',food: '胡萝卜',favor: '刨洞'
          },{
              id: '00004',name: '狮',food: '肉',favor: '猎物'
          }
        ];
        $scope.AniID = '00004';
        $scope.$watch('AniID',function (newValue) {
            console.info(newValue);
        });
    });
原文链接:https://www.f2er.com/angularjs/149172.html

猜你在找的Angularjs相关文章