angularJS- ng-options 和ng-repeat创建select

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/stu_20052369/article/details/87099931
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <h2>1.使用 ng-options 指令</h2>
        <!--ng-options 指令创建的下拉列表,选中的值是一个对象, 所以建议使用 ng-option来创建select -->
        <p>选择水果:</p>
        <!-- ng-model 和 ng-init 里面绑定的变量名需要一样 -->
        <select ng-model="selectedFruit" ng-init="selectedFruit= fruits[1]" ng-options="x.Alias for x in fruits">
        </select>
        <p>你选择的是: {{selectedFruit.name}}</p>
        <p>别名为: {{selectedFruit.Alias}}</p>
        <p>单价为: {{selectedFruit.price}}</p>

        <h2>2.使用 ng-repeat 指令</h2>
        <!-- ng-repeat 指令创建的下拉列表,选中的值是一个值。 -->
        <p>选择水果:</p>
        <select ng-model="selectedFruit2" ng-init="selectedFruit2= fruits[1].name">
            <option ng-repeat="x in fruits" value="{{x.name}}">{{x.Alias}}</option>
        </select>

        <p>你选择的是: {{selectedFruit2}}</p>

        <h2>3.数据源为对象</h2>

        <p>选择水果:</p>
        <select ng-model="selectedFruit3" ng-init="selectedFruit3= fruits3.fruit1" ng-options="x for (x,y) in fruits3">
        </select>
        <select ng-model="selectedFruit3" ng-init="selectedFruit3= fruits3['fruit1']" ng-options="x for (x,y) in fruits3">
        </select>

        <p>你选择的是: {{selectedFruit3.name}}</p>
        <p>别名为: {{selectedFruit3.Alias}}</p>
        <p>单价为: {{selectedFruit3.price}}</p>

        <p>或者</p>
        <p>选择水果:</p>
        <select ng-model="selectedFruit4" ng-options="y.Alias for (x,y) in fruits3">
        </select>

        <p>你选择的是: {{selectedFruit4.name}}</p>
        <p>别名为: {{selectedFruit4.Alias}}</p>
        <p>单价为: {{selectedFruit4.price}}</p>

    </div>
    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.fruits = [
                { name: 'apple', Alias: "苹果", quantity: 100, price: 4.00 },
                { name: 'orange', Alias: "橘子", quantity: 200, price: 2.00 },
                { name: 'banana', Alias: "香蕉", quantity: 300, price: 3.50 }];
            $scope.fruits3 = {
                fruit1: { name: 'apple', Alias: "苹果", quantity: 100, price: 4.00 },
                fruit2: { name: 'orange', Alias: "橘子", quantity: 200, price: 2.00 },
                fruit3: { name: 'banana', Alias: "香蕉", quantity: 300, price: 3.50 }
            }
            $scope.selectedFruit4 = $scope.fruits3.fruit1;
        });
    </script>

</body>

</html>

猜你喜欢

转载自blog.csdn.net/stu_20052369/article/details/87099931