选择,使用ng-repeat,不显示ng-model的当前值

时间:2017-01-18 17:33:12

标签: javascript html angularjs

我上面有这个代码:

Performing system checks...

SKIPPING SYSTEM CHECKS!

SKIPPING MIGRATION CHECKS!

January 18, 2017 - 12:18:06
Django version 1.10.2, using settings 'foo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

问题是,ng模型当前值(甚至在选择了一个选项之前),没有显示在该字段上。这是空白的。有人可以帮忙吗? 谢谢

2 个答案:

答案 0 :(得分:0)

您应该使用ng-options而不是重复选项 检查这个小提琴 - https://plnkr.co/edit/XpgXNOPjC9ZJ8lYuPhGP?p=preview

angular.module("sampleApp", [])
  .controller("sampleController", function() {

    var vm = this;
    vm.availableModulos = [
        {value: "Value 1"}
        {value: "Value 2"},
        {value: "Value 3"},
        {value: "Value 4"},
        {value: "Value 5"}
    ];        
    vm.modulo = {nomenclatura: vm.availableModulos[2]};    
  });  

<body data-ng-controller="sampleController as vm">
    {{vm.modulo.nomenclatura}}
    <select ng-model = "vm.modulo.nomenclatura"     class="form-control" required ng-options="mod as mod.value for mod in vm.availableModulos">
      <option></option>
      </select>
  </body>

答案 1 :(得分:0)

使用角度选择标记的最佳做法是使用ng-options而不是使用ng-repeat内部选项。使用角度ng选项和track by表达式来跟踪模型值。应该有一个唯一的id字段,应该按键跟踪提供。将根据跟踪值初始化模型。

这是一个有效的演示。

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>

<body>

    <div ng-app="myApp" ng-controller="myCtrl as vm">
        <select ng-model="vm.modulo.nomenclatura" class="form-control" required ng-options="option.value for option in vm.availableModulos track by option.id"> </select>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope, $timeout) {
            var _self = this;
            _self.availableModulos = [ { value: "Value 1", id: 0 },
                                    { value: "Value 2", id: 1 },
                                    { value: "Value 3", id: 2 },
                                    { value: "Value 4", id: 3 },
                                    { value: "Value 5", id: 4 }
                        ];
            _self.modulo = {
                nomenclatura: _self.availableModulos[2]
            };
        });
    </script>

</body>

</html>