mirko911 mirko911 - 1 year ago 74
Javascript Question

AngularJS fill $scope.selected with object from <select>

I have a problem with filling a scope with the correct data an keeping the correct attribute.

I've a small PHP script which returns an id, a name and a time as json array.

"times": [
"id": "myID",
"name": "myName",
"time": "40:00:00"
...(10 more objects)

I want to create a dropdown element with the name as name and the id as value. I did this over a
and this works very well.

<select name="StPl_Code" class="form-control" id="field-stpl-name" ng-model="selected">
<option ng-repeat="i in times" value="{{i.id}}">{{i.name}}</option>

My problem is, that I want to save the selected
to use it's time value for an other input field without losing the value in the value attribute

Here is my angular code

app.controller('auftraegeCrtl', function($scope, $http){
$scope.selected = '';
$http.get('index.php?page=times&json=true').success(function(data, status, headers, config){
$scope.times = data.times;
}).error(function(data, status, headers, config){

Answer Source

You will want to use the ng-options directive, like this:

<select name="StPl_Code" class="form-control" id="field-stpl-name" ng-model="selected" ng-options="i.id as i.name for i in times"></select>

You can see it working here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download