[javascript] AngularJs - ng-model in a SELECT

JSfiddle

Problem:

I have a SELECT-element in my page, which is filled in with an ng-repeat. It also has a ng-model which has a default value.

When I change the value, the ng-model adapts, that's ok. But the dropdown-list shows an empty slot at launch, where it should have the item with the default value selected instead.

Code

<div ng-app ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
         <option ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

With JS:

function myCtrl ($scope) {
    $scope.units = [
        {'id': 10, 'label': 'test1'},
        {'id': 27, 'label': 'test2'},
        {'id': 39, 'label': 'test3'},
    ]

        $scope.data = {
        'id': 1,
        'unit': 27
        }

};

This question is related to javascript jquery angularjs angular-ngmodel

The answer is


However, ngOptions provides some benefits such as reducing memory and increasing speed by not creating a new scope for each repeated instance. angular docs

Alternative solution is use ng-init directive. You can specify function that will be initialize your default data.

$scope.init = function(){
            angular.forEach($scope.units, function(item){
                if(item.id === $scope.data.unit){
                    $scope.data.unit = item;
                }
            });
        } 

See jsfiddle


You can also put the item with the default value selected out of the ng-repeat like follow :

<div ng-app="app" ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
        <option value="yourDefaultValue">Default one</option>
        <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

and don't forget the value atribute if you leave it blank you will have the same issue.


Select's default value should be one of its value in the list. In order to load the select with default value you can use ng-options. A scope variable need to be set in the controller and that variable is assigned as ng-model in HTML's select tag.

View this plunker for any references:

http://embed.plnkr.co/hQiYqaQXrtpxQ96gcZhq/preview


try the following code :

In your controller :

 function myCtrl ($scope) {
      $scope.units = [
         {'id': 10, 'label': 'test1'},
         {'id': 27, 'label': 'test2'},
         {'id': 39, 'label': 'test3'},
      ];

   $scope.data= $scope.units[0]; // Set by default the value "test1"
 };

In your page :

 <select ng-model="data" ng-options="opt as opt.label for opt in units ">
                </select>

Working Fiddle


You dont need to define option tags, you can do this using the ngOptions directive: https://docs.angularjs.org/api/ng/directive/ngOptions

<select class="form-control" ng-change="unitChanged()" ng-model="data.unit" ng-options="unit.id as unit.label for unit in units"></select>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to angular-ngmodel

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'" Get user input from textarea AngularJs - ng-model in a SELECT Angular bootstrap datepicker date format does not format ng-model value Radio Buttons ng-checked with ng-model How to set a selected option of a dropdown list control using angular JS Ng-model does not update controller value What's the difference between ng-model and ng-bind AngularJS : ng-model binding not updating when changed with jQuery