Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select dropdown not binding initially to AngularJS model

Ok so my issue is that I have a simple select dropdown, and am using ng-repeat to populate the dropdown, like below:

<select ng-model="tstCtrl.model.value" required>
  <option ng-repeat="option in tstCtrl.myOptions" value="{{option.a}}">{{option.b}}</option>
</select>

After selecting an option, the binding to model.value works fine, but until then it doesn't seem to bind the selected dropdown option to the value model.value is initially set to.

This is demonstrated below:

<!DOCTYPE html>
<html>

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>

  <script>
    angular.module('Test', []).controller('TestController', function(){
      
      this.model = {
        value:3
      };
      
      this.myOptions = [
        {a:1, b:"one"},
        {a:2, b:"two"},
        {a:3, b:"three"},
        {a:4, b:"four"},
        {a:5, b:"five"}];
    });
  </script>
  </head>

  <body ng-app="Test" ng-controller="TestController as tstCtrl">

    {{tstCtrl.model.value}}

    <select ng-model="tstCtrl.model.value" required>
      <option ng-repeat="option in tstCtrl.myOptions" value="{{option.a}}">{{option.b}}</option>
    </select>

  </body>



</html>

I think the above snippet makes it really clear, but am happy to answer any questions.

How do I solve this?

Thanks

like image 747
JMK Avatar asked Feb 09 '23 22:02

JMK


1 Answers

I suggest you use the ng-options syntax instead of an ng-repeat inside your select. If you want to display property b but bind to property a you can use the following syntax:

<select ng-model="model.value" ng-options="option.a as option.b for option in myOptions" required>      
</select>

Here's your modified working snippet:

<!DOCTYPE html>
<html>

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>

  <script>
    angular.module('Test', []).controller('TestController', function($scope){
      
      $scope.model = {
        value:3
      };
      
      $scope.myOptions = [
        {a:1, b:"one"},
        {a:2, b:"two"},
        {a:3, b:"three"},
        {a:4, b:"four"},
        {a:5, b:"five"}];
    });
  </script>
  </head>

  <body ng-app="Test" ng-controller="TestController">

    {{model.value}}

    <select ng-model="model.value" ng-options="option.a as option.b for option in myOptions"  required>      
    </select>

  </body>



</html>
like image 84
yvesmancera Avatar answered Feb 11 '23 14:02

yvesmancera