PHP群:95885625 Hbuilder+MUI群:81989597 站长QQ:634381967
    您现在的位置: 首页 > 开发编程 > AngularJS教程 > 正文

    AngularJS Select(选择框)

    作者:admin来源:网络浏览:时间:2020-09-30 00:07:50我要评论
    导读:AngularJS Select(选择框)AngularJS 可以使用数组或对象创建一个下拉列表选项。使用 ng-options 创建选择框在 AngularJS 中我们可以...

    AngularJS Select(选择框)

    AngularJS 可以使用数组或对象创建一个下拉列表选项。


    使用 ng-options 创建选择框

    在 AngularJS 中我们可以使用 ng-option 指令来创建一个下拉列表,列表项通过对象和数组循环输出,如下实例:
     

    1. <div ng-app="myApp" ng-controller="myCtrl"
    2.  
    3. <select ng-model="selectedName" ng-options="x for x in names"
    4. </select> 
    5.  
    6. </div> 
    7.  
    8. <script> 
    9. var app = angular.module('myApp', []); 
    10. app.controller('myCtrl'function($scope) { 
    11.     $scope.names = ["Google""Runoob""Taobao"]; 
    12. }); 
    13. </script> 

    ng-options 与 ng-repeat

    我们也可以使用ng-repeat 指令来创建下拉列表:
     

    1. <select> 
    2. <option ng-repeat="x in names">{{x}}</option> 
    3. </select> 

    ng-repeat 指令是通过数组来循环 HTML 代码来创建下拉列表,但 ng-options 指令更适合创建下拉列表,它有以下优势:

    使用 ng-options 的选项的一个对象, ng-repeat 是一个字符串。


    应该用哪个更好?

    假设我们使用以下对象:
     

    1. $scope.sites = [ 
    2.     {site : "Google", url : "http://www.google.com"}, 
    3.     {site : "Runoob", url : "http://www.runoob.com"}, 
    4.     {site : "Taobao", url : "http://www.taobao.com"
    5. ]; 

    ng-repeat 有局限性,选择的值是一个字符串:
    使用 ng-repeat:

    1. <select ng-model="selectedSite"
    2. <option ng-repeat="x in sites" value="{{x.url}}">{{x.site}}</option> 
    3. </select> 
    4.  
    5. <h1>你选择的是: {{selectedSite}}</h1> 

    使用 ng-options 指令,选择的值是一个对象:
    使用 ng-options:

    1. <select ng-model="selectedSite" ng-options="x.site for x in sites"
    2. </select> 
    3.  
    4. <h1>你选择的是: {{selectedSite.site}}</h1> 
    5. <p>网址为: {{selectedSite.url}}</p> 

    当选择值是一个对象时,我们就可以获取更多信息,应用也更灵活。


    数据源为对象

    前面实例我们使用了数组作为数据源,以下我们将数据对象作为数据源。
     

    1. $scope.sites = { 
    2.     site01 : "Google"
    3.     site02 : "Runoob"
    4.     site03 : "Taobao" 
    5. }; 

    ng-options 使用对象有很大的不同,如下所示:
    使用对象作为数据源, x 为键(key), y 为值(value):

    1. $scope.cars = { 
    2. car01 : {brand : "Ford", model : "Mustang", color : "red"}, 
    3. car02 : {brand : "Fiat", model : "500", color : "white"}, 
    4. car03 : {brand : "Volvo", model : "XC90", color : "black"
    5. }; 

    在下拉菜单也可以不使用 key-value 对中的 key , 直接使用对象的属性:

    1. <select ng-model="selectedCar" ng-options="y.brand for (x, y) in sites"
    2. </select> 

     

    转载请注明(B5教程网)原文链接:https://b5.mxunkeji.com/content-152-3425-1.html
    相关热词搜索:
    下一篇:AngularJS 表格