当前位置 主页 > 网站技术 > 代码类 >

    AngularJS动态生成select下拉框的方法实例

    栏目:代码类 时间:2019-11-17 15:06

    一、select相关知识

    <select>
    	<option value="0">HTML</option>
     <option value="1">Java</option>
     <option value="2">Python</option>
    </select>

    其中,value 是存储到数据库的值,在此处为0,1,2这些数值,label 为显示在页面的值,在此处为Html、Java这些字符。

    二、ng-options

    1.数组作为数据源

    label for value in array select as label for value in array label group by group for value in array

    代码1(数组中为字符串)

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
    </head>
    <body>
    
    <div ng-app="myApp" ng-controller="myCtrl">
     <!--
    		这里的label和value需一致,否则会报错
    		表达式语法:label for value in array
    	-->
    	<select ng-model="name" ng-options="name for name in names"></select>
    </div>
    
    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
     $scope.names = ['baidu', 'Google', 'apple'];
    });
    </script>
    </body>
    </html>

    最终得到的结果为:

    <select ng-model="name" ng-options="name for name in names" class="ng-pristine ng-valid ng-touched">
     <option value="?" selected="selected"></option>
     <option value="string:baidu" label="baidu">baidu</option>
     <option value="string:Google" label="Google">Google</option>
     <option value="string:apple" label="apple">apple</option>
    </select>

    需要注意的是,在最后生成的html代码中option的value 值为String:baidu ,会在数组中原有的字符串之前加上其类型的标识,这个通过百度了解到是因为angularjs版本问题造成,具体未测试。

    代码2(数组中为一个对象)

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
    </head>
    <body>
    <div ng-app="myApp" ng-controller="myCtrl">
     <!--
    		表达式语法:label for value in array
    	-->
    	<select ng-model="name" ng-options="c.id for c in coms"></select>
    </div>
    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
     $scope.coms = [
      {'id':'baidu','name':'百度'}, 
      {'id':'Google', 'name':'谷歌'}, 
      {'id':'apple', 'name':'苹果'}];
    });
    </script>
    </body>
    </html>

    最终得到的html代码为:

    <!-- 注意:此处ng-model绑定的name变量并非选中项的name属性,而是选中项的全部属性
    	如选中了索引为0项,则name={"id":"baidu","name":"百度"}
    	这边ng-model绑定变量为值为select的value值
    -->
    <select ng-model="name" ng-options="c.id for c in coms" class="ng-pristine ng-valid ng-touched">
     <option value="?" selected="selected"></option>
     <option value="object:3" label="baidu">baidu</option>
     <option value="object:4" label="Google">Google</option>
     <option value="object:5" label="apple">apple</option>
    </select>