AngularJS:如何创建选择选项并设置默认选择选项?

时间:2014-09-24 12:13:08

标签: angularjs forms

我使用AngularJS创建一个html表单。所以在我的表单中我有2个文本输入和选择选项。代码如下:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<script>
    angular.module("myapp", [])
            .controller("MyController", function($scope) {
                $scope.myForm = {};
                $scope.myForm.firstName = "Jakob";
                $scope.myForm.lastName = "Nielsen";
                $scope.myForm.town  = {name:"Not filled", value:"0"};
                $scope.towns  = [
                                            {name:"Not filled", value:"0"},
                                            {name:"New York", value:"1"},
                                            {name:"San Francisco", value:"2"},
                                            {name:"Boston", value:"3"},
                                            {name:"Miami", value:"4"}
                                        ];
            } );
</script>
<body ng-app="myapp">

<div ng-controller="MyController" >
    <form>
         First name : <input type="text" name="firstName" ng-model="myForm.firstName"> <br/>
         Last name : <input type="text" name="lastName"  ng-model="myForm.lastName">  <br/>
         Town : 
         <select ng-model="myForm.town" ng-options="town.value as town.name for item in towns"></select>



    </form>

    {{myForm.firstName}} | {{myForm.lastName}} | {{myForm.town.name}} | {{myForm.town.value}}

    <div>

</body>
</html>

我面临两个问题: 我看不到选项标签。我不明白。我使用答案here来编写我的选择选项。请问有什么不对? 2.在我的控制器中,我将选择选项的模型设置为默认选择一个选项。我想知道它是否是正确的方法呢?

$scope.myForm.town  = {name:"Not filled", value:"0"};

感谢您的帮助。这是我的plunker link

2 个答案:

答案 0 :(得分:1)

是的我认为在模型中设置默认值是没关系的,我没有看到它的问题。

关于您的标签问题,您使用了错误的迭代器item in towns,应该是town in towns

<select ng-model="myForm.town" ng-options="town.value as town.name for town in towns"></select>

答案 1 :(得分:1)

我在这里修理了你的傻瓜: http://plnkr.co/edit/pJyOGUtBRiaoeFYeEDFD?p=preview

问题是:

  1. ng-options中的语法错误。应该是:item.name for item in townstown.name for town in towns

  2. 您必须将所选值设置为源中的一个对象 - 而不是新对象:$scope.myForm.town = $scope.towns[0];

  3. 您可以采用另一种方法解决问题2.如果您不想引用正确的对象$scope.towns[0],则可以通过指定track by来更改角度跟踪模型的方式。您需要将ng-options更改为town.name for town in towns track by town.value,然后按以下方式设置所选索引:$scope.myForm.town = {value : "1"};