angularjs小練習(分別通過ng-repeat和ng-option動態生成select下拉框), 在實現上有兩種方式:其一、通過ng-repeat來實現;其二、通過ng-option來實現 ...
本次做一個簡單的關於動態生成select的練習
在實現上有兩種方式:
其一、通過ng-repeat來實現
其二、通過ng-option來實現
在頁面效果上,兩種實現的效果都一樣
但是在數據選擇的數據從操作上有所不同
ng-repeat選中的是其option對應的value值
ng-option選擇的是其對應綁定數據的一個object對象
在實際應用中建議採用ng-option實現
代碼實例:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body ng-app="myApp"> <div ng-controller="CityController"> <div style="margin-bottom: 40px;"> <h1>通過ng-options實現</h1> <select ng-model="city" id="selectCity1" ng-options="city1.name for city1 in cities"> <option value="">請選擇</option> </select> 所選擇的城市信息: {{ city }} </div> <div style="margin-bottom: 40px;"> <h1>通過ng-repeat實現</h1> <select ng-model="city2" id="selectCity2"> <option value="" selected="selected">請選擇</option> <option ng-repeat="city in cities" value="{{city.id}}">{{city.name}}</option> </select> 所選擇的城市ID: {{ city2 }} </div> <div> <input type="text" ng-model="newCityName" placeholder="請輸入新增城市的名稱" /> <input type="button" ng-click="addCity()" value="新增城市" /> </div> </div> </body> </html> <script src="../JS/angular.js"></script> <script type="text/javascript"> var app = angular.module("myApp", []); app.controller("CityController", function ($scope) { //// 初始化城市數據 $scope.cities = [ { name: '成都', id: 1 }, { name: '南充', id: 2 }, { name: '綿陽', id: 3 }, { name: '達州', id: 4 }, { name: '瀘州', id: 5 } ]; //// 新增一個城市信息 $scope.addCity = function () { if ($scope.newCityName) { $scope.cities.push({ name: $scope.newCityName, id: $scope.getCityMaxId() + 1 }); } } //// 獲取已有城市列表中城市ID最大值 $scope.getCityMaxId = function () { var cityIdArry = new Array(); for (var i in $scope.cities) { cityIdArry.push($scope.cities[i].id); } cityIdArry.sort(function (num1, num2) { return num1 - num2; }); return cityIdArry[cityIdArry.length - 1]; }; }); </script>