当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


AngularJS ng-options用法及代码示例


AngularJS中的ng-options指令用于构建HTML元素并将其与选项绑定到模型属性。它用于在<选择>列表中指定<选项>。它是专门为填充下拉列表中的项目而设计的。 <supported>元素支持它。

用法:

<element ng-options="expression"> Content ... </element> 

范例1:本示例使用ng-options指令显示选项元素。


<!DOCTYPE html> 
<html> 
  
<head> 
    <title>ng-options Directive</title> 
      
    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
    </script> 
</head> 
  
<body ng-app="app" style="text-align:center"> 
      
    <h1 style="color:green">GeeksforGeeks</h1> 
    <h2>ng-options Directive</h2>                              
      
    <div ng-controller="geek" ng-init="StudentId=1"> 
        Sorting Algorithms:  
        <select ng-model="Sorting" ng-options="sort.name as  
            sort.name for sort in sorting"></select> 
          
        <br><br><br><br><br> 
          
        Selected sorting algorithm:  
        <input type="text" ng-model="Sorting" /> 
    </div> 
      
    <script> 
        var app = angular.module("app", []); 
        app.controller('geek', ['$scope', function ($scope) { 
            $scope.sorting = [ 
                { name:'Merge sort', id:1 },  
                { name:'Quick sort', id:2 },  
                { name:'Bubble sort', id:3 } 
            ]; 
        }]); 
    </script> 
</body> 
  
</html>                    

输出:
选择元素之前:
ngoptions
选择元素后:
ngoptions

范例2:本示例使用ng-options指令隐藏或显示元素。

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>ng-options Directive</title> 
      
    <script src= 
    "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
    </script> 
</head> 
  
<body ng-app="app" style="text-align:center"> 
      
    <h1 style="color:green">GeeksforGeeks</h1> 
    <h2>ng-options Directive</h2>                                
      
    <div ng-controller="geek" ng-init="Id=1"> 
        Choose:<select ng-model="hide" ng-options="show.hide 
            as show.name for show in HideShow"></select> 
      
        <br><br><br> 
          
        <span ng-hide="hide">  
            Check to hide <input type="checkbox"
                    ng-model="hide" /> 
        </span> 
    </div> 
      
    <script> 
        var app = angular.module("app", []); 
        app.controller('geek', ['$scope', function ($scope) { 
            $scope.HideShow = [ 
                { name:'Hide', hide:true, },  
                { name:'Show', hide:false } 
            ]; 
        }]); 
    </script> 
</body> 
  
</html>

输出:
选择隐藏元素之前:
ngoptions
选择hide元素后:
ngoptions



相关用法


注:本文由纯净天空筛选整理自Vishal Chaudhary 2大神的英文原创作品 AngularJS | ng-options Directive。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。