如何在Angular JS中选择带对象的选项?

时间:2015-05-01 10:35:42

标签: angularjs

有对象:

   $scope.type = {
        1 : 'Inside',
        2 : 'Outside'
    };

HTML ng-options:

 <select ng-options="key as value for (key , value) in type" ng-model="selectedType"></select>

我试过了:

$scope.selectedType = (UserGlobalService.type == 1) ? $scope.records[1] : $scope.records[2];

2 个答案:

答案 0 :(得分:2)

嗨这可以解决你的问题

的index.html

<html lang="en" ng-app='myApp'>
    <head>

        <title>My AngularJS App</title>

        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
        <!-- Modules -->
        <script src="app.js"></script>
    </head>
    <body ng-controller ='MainController'>
        <div>

            <select class="form-control" >
            <!-- <option ng-value= "{{item}}" >{{item}}</option> -->
            <option ng-repeat="option in type" value="{{option.value}}" ng-selected="type.value == option.value">{{option.value}}
            </option>

        </select>               
        </div>

    </body>

你的JS应该是这样的。

var myApp = angular.module('myApp', []);

myApp.controller('MainController', ['$scope',
    function($scope) {
        $scope.type = [{
               "id" : 1,
               "value" : "Inside"
             },{
                "id" : 2,
               "value" : "Outside"
            }];        
    }
])

答案 1 :(得分:1)

我编辑了我的答案

我就是这样做的:

$scope.types = [
   { id: 1, name: 'Inside' },
   { id: 2, name: 'Outside' }];

$scope.selectedType = $scope.type[0];

HTML:

<select ng-options="t.name for t in types" ng-model="selectedType"></select>

这里的“傻瓜:http://plnkr.co/edit/uyP5EeOUTQb7n1ymsFuB