setting Angular select ng-init to first value in array

simplesthing picture simplesthing · Jan 3, 2014 · Viewed 92.1k times · Source

I have a simple select element that I am trying to enforce a value being present to submit the form and I have tried both setting the required attribute as well as using ng-init to ensure there is a value selected and both fail.

I am using ng-options to create a list of values from an array of Objects that have a ref property. Then I would like to use ng-init to set the shown value to the first Object.ref in the array.

<select name="refmarker" class="input-block-level form-width-adjust" ng-model="model.refmarker" ng-options="rm.ref for rm in refmarkers" ng-disabled="editable" ng-init="model.refmarker='refmarkers[0].ref'" required></select>

I have tried the following without any luck

ng-init="model.refmarker='refmarkers[0]'"
ng-init="model.refmarker='refmarkers[0].ref'"
ng-init="model.refmarker='rm.ref'"

Also the required attribute doesn't work ? Is the angular select element buggy or am I doing something wrong?

Answer

Noishe picture Noishe · Jan 3, 2014

required will only work in side a form element.

What you want is ng-init="model.refmarker=refmarkers[0]"

<!doctype html>
<html lang="en" data-ng-app="app">
<head>
    <meta charset="utf-8">
    <title>Test</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
    <script type="text/javascript">

        angular.module('app',[])
                .controller('Main',function($scope)
                {
                    $scope.model = {};
                    $scope.refmarkers = [{ref:'abc'},{ref:'def'},{ref:'ghi'}];
                });
    </script>
</head>
<body ng-controller="Main">
{{'Angular'}}
<select ng-model="model.refmarker" ng-options="rm.ref for rm in refmarkers" ng-init="model.refmarker=refmarkers[0]"></select>
{{model.refmarker}}
</body>
</html>