This is a simple exercise about dynamically generating select
There are two ways to implement it:
First, through ng repeat
Second, through ng option
In terms of page effect, the effect of both implementations is the same
But the operation of data selection is different
Ng repeat selects the value corresponding to its option
Ng option selects an object object object corresponding to the binding data
In practical application, ng option is recommended
Code instance:
<!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>adopt ng-options Realization</h1> <select ng-model="city" id="selectCity1" ng-options="city1.name for city1 in cities"> <option value="">Please choose</option> </select> //Selected city information: {{City}} </div> <div style="margin-bottom: 40px;"> <h1>adopt ng-repeat Realization</h1> <select ng-model="city2" id="selectCity2"> <option value="" selected="selected">Please choose</option> <option ng-repeat="city in cities" value="{{city.id}}">{{city.name}}</option> </select> //Selected city ID: {{city2}}} </div> <div> <input type="text" ng-model="newCityName" placeholder="Please enter the name of the new city" /> <input type="button" ng-click="addCity()" value="New cities" /> </div> </div> </body> </html> <script src="../JS/angular.js"></script> <script type="text/javascript"> var app = angular.module("myApp", []); app.controller("CityController", function ($scope) { //// Initialize city data $scope.cities = [ { name: 'Chengdu', id: 1 }, { name: 'Nao', id: 2 }, { name: 'Mianyang', id: 3 }, { name: 'Dazhou', id: 4 }, { name: 'Luzhou', id: 5 } ]; //// Add a new city information $scope.addCity = function () { if ($scope.newCityName) { $scope.cities.push({ name: $scope.newCityName, id: $scope.getCityMaxId() + 1 }); } } //// Get the maximum value of City ID in the existing city list $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>