angularjs小练习(分别通过ng-repeat和ng-option动态生成select下拉框)

2018-08-31 09:42:32 浏览数 (1)

本次做一个简单的关于动态生成select的练习

  在实现上有两种方式:

    其一、通过ng-repeat来实现

    其二、通过ng-option来实现

    在页面效果上,两种实现的效果都一样

    但是在数据选择的数据从操作上有所不同

    ng-repeat选中的是其option对应的value值

    ng-option选择的是其对应绑定数据的一个object对象

  在实际应用中建议采用ng-option实现

  代码实例:

代码语言:javascript复制
<!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>

0 人点赞