javascript - How to set a default ngOptions value, when options are objects, and default is an integer ID -
i'm working ngoptions display select element, , want connect model value that's set value in ngoptions.
var app = angular.module('test', []); app.controller('testctrl', ['$scope', function ($scope) { //use random simulate different data api $scope.default = math.floor(math.random()*3); $scope.options = [ { id: 0, name: "option 1" }, { id: 1, name: "option 2" }, { id: 2, name: "option 3" } ]; }]); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="test"> <div ng-controller="testctrl"> <select ng-model="default" ng-options="val.name val in options track val.id"> </select> <pre>default should id {{default}}, or option {{default+1}} </div> </div> i've tried using track by, select as, , i've found 2 solutions work, not ideal.
ideally, i'd able set default
solution 1:
// loop through entire array of objects $scope.options.foreach(function (v, k) { // compare id default should if (v.id === $scope.default) { // set object default $scope.default = v; return true; } }); solution 2:
js
$scope.options = { "option 1": 0, "option 2": 1, "option 3": 2 }; html
<select ng-model="default" ng-options="value key (key, val) in options"> the thing that's tough solution works if object has no more 2 values, since key cannot object.
is there way have angular set default key, without having include entire object?
try this
<select ng-options="item.id item.name item in options" ng-model="selected"></select> then in controller
$scope.selected = 1;
Comments
Post a Comment