【MVVM】- AngularJS 下拉框操作

情到浓时终转凉″ 提交于 2021-01-12 07:03:10

AngularJS 下拉框基础应用

外观界面

<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names"></select>
等价于:
<select>
<option ng-repeat="item in names">{{item}}</option>
</select>

<hr>
<!-- ng-repeat绑定的值为一个字符串,ng-options绑定的为一个对象 -->
<select ng-model="selectedSIte">
<option ng-repeat="item in sites" value="{{item.url}}">{{item.site}}</option>
</select>
<span>你选中的选址:{{selectedSIte}}</span>

<br><br>
<select ng-model="selectedSite" ng-options="x.site for x in sites"></select>
<span>你选中的选址:{{selectedSite}}</span>

<hr>
<!-- 因为对象数组没有key,angular默认使用数组的下标值作为key显示 -->
<select ng-model="AAAA" ng-options="x for (x, y) in sites"></select>
<span>你选择的值是: {{AAAA}}</span>
</div>

js操作逻辑

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Google", "Baidu", "Taobao"];
$scope.sites = [{
 site : "Google", url : "http://www.google.com"},
{site : "Baidu", url : "http://www.baidu.com"},
{site : "Taobao", url : "http://www.taobao.com"} ];
});

效果:


AngularJS 下拉框高级应用

外观正文

<body ng-app="myApp">

<!-- 对象内部属性遍历:x--key  y---value -->
<div  ng-controller="myctr01">
{{sites}}<br>
<select ng-model="site" ng-options="x for (x, y) in sites"></select>
选择的网址:<span>{{site}}</span>
</div>

<div  ng-controller="myCtrl">
<p>选择一辆车:</p>
<!-- 这里y标识成员元素对象,并且使用该对象的brand属性作为显示文本,select的值与y绑定 -->
<select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars"></select>
<p>你选择的是: {{selectedCar.brand}}</p>
<p>型号为: {{selectedCar.model}}</p>
<p>颜色为: {{selectedCar.color}}</p>
<p>下拉列表中的选项也可以是对象的属性。</p>
</div>

js操作逻辑

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    //复杂对象
$scope.cars = {
car01 : {brand : "Ford", model : "Mustang", color : "red"},
car02 : {brand : "Fiat", model : "500", color : "white"},
car03 : {brand : "Volvo", model : "XC90", color : "black"} }
   
   //简单对象
   $scope.sites = {
           site01 : "Google",
           site02 : "Baidu",
           site03 : "Taobao"
       };
});

app.controller("myctr01",function($scope){
    $scope.sites = {
            site01 : "Google",
            site02 : "Baidu",
            site03 : "Taobao"
        };
});

效果:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!