Small exercise of angularjs (dynamically generate the select drop-down box through ng repeat and ng option respectively)

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="">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<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=" for city1 in cities">
                <option value="">Please choose</option>
            //Selected city information: {{City}}
        <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="{{}}">{{}}</option>
            //Selected city ID: {{city2}}}
            <input type="text" ng-model="newCityName" placeholder="Please enter the name of the new city" />
            <input type="button" ng-click="addCity()" value="New cities" />
<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.sort(function (num1, num2) {
                return num1 - num2;
            return cityIdArry[cityIdArry.length - 1];

Keywords: Javascript angular

Added by mega_hurtz on Fri, 03 Jan 2020 10:52:00 +0200