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

2022-11-30 HTMLXMLAngularJS

本次做一个简单的关于动态生成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>

上一篇:从Workflowy到印象笔记

下一篇:angularjs学习第八天笔记(指令作用域研究)