mirko911
mirko911

Reputation: 353

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 ng-repeat 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>
</select>

My problem is, that I want to save the selected i in $scope.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){
      });
  });

Upvotes: 0

Views: 1961

Answers (3)

jkris
jkris

Reputation: 6511

Use 'Ng-options' instead.

<select ng-options="i as i.name for i in times track by item.id" ng-model="selected"></select>

This will set $scope.selected to the object selected

Upvotes: 0

Massi Issar
Massi Issar

Reputation: 403

Try this :

 $scope.selected = {};

instead of :

 $scope.selected = '';

Upvotes: 0

jbrown
jbrown

Reputation: 3025

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

Upvotes: 1

Related Questions