1

I have this code above:

<select ng-model = "vm.modulo.nomenclatura" class="form-control" required>
 <option></option>
 <option ng-value="modulo.key" ng-repeat="modulo in vm.availableModulos">{{modulo.value}}</option>
</select>

The thing is, the ng-model current value (even before been selected an option), does not shows up on the field. It's blank. Could somebody help? Thank you

2 Answers2

0

You should be using ng-options instead of repeating the options Check this fiddle out - 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>
Developer
  • 6,240
  • 3
  • 18
  • 24
0

The best practice in using angular select tag is using ng-options rather than using ng-repeat inside options. Use angular ng-options and track by expression to track your model value. There should be a unique id field that should be provided as track by key. Th ng-model will be initialized on the basis of the track by value.

Here is a working demo.

<!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>
Community
  • 1
  • 1
Nitheesh
  • 19,238
  • 3
  • 22
  • 49