AngularJS Select(選擇框)



在AngularJS中可以使用數組或對象創建一個下拉列表對象選項。

1、使用ng-options創建選擇框

 

 

 

<div ng-app="my" ng-controller="con">
            <p>請選擇城市:</p>
            <select ng-model="selected" ng-options="x for x in city"></select>
            
            
            
        </div>
        <script>
            
            var app=angular.module("my",[]);
            app.controller("con",function($scope){
                
                $scope.city=["北京","上海","廣州","福建","深圳"];
            })
        </script>

 

 ng-options 指令來創建一個下拉列表,列表項是通過對象和數組循環輸出。

 

ng-repeat指令也可以實現下拉列表哦!!!它是通過數組來循環 HTML 代碼來創建下拉列表:

 

 

實現代碼:

	<!--ng-repeat-->
		<div ng-app="my" ng-controller="con">
			<p>請選擇城市:</p>
			<select>
				<option ng-repeat="x in city">{{x}}</option>
			</select>
			
			
			
		</div>
		<script>
			
			var app=angular.module("my",[]);
			app.controller("con",function($scope){
				
				$scope.city=["北京","上海","廣州","福建","深圳"];
			})
		</script>

  

 由於ng-options指令具有以下的優勢,因此它更適合創建下拉列表。

1、ng-options 的選項是一個對象。而ng-repeat 是一個字符串

2、ng-options指令選擇的值是一個對象,而ng-repeat具有局限性,選擇的值是一個字符串

當選擇值是一個對象時,我們就可以獲取更多信息,應用也更靈活。

 

 

 

 

<div ng-app="myApp" ng-controller="myCtrl">

<p>選擇網站:</p>

<select ng-model="selectedSite" ng-options="x.site for x in sites">
</select>

<h1>你選擇的是: {{selectedSite.site}}</h1>
<p>網址為: {{selectedSite.url}}</p>

</div>
<div ng-app="my" ng-controller="">
<select ng-model="selectedSite">
<option ng-repeat="x in sites" value="{{x.url}}">{{x.site}}</option>
</select>

<h1>你選擇的網址:(ng-repeat): {{selectedSite}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.sites = [
        {site : "Google", url : "http://www.google.com"},
        {site : "bokeyuan", url : "https://www.cnblogs.com"},
        {site : "Taobao", url : "http://www.taobao.com"}
    ];
});
</script>
        

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM