setting Angular select ng-init to first value in array

天大地大妈咪最大 提交于 2019-12-09 14:51:12

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/20894934/setting-angular-select-ng-init-to-first-value-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!