svichkar
svichkar

Reputation: 1856

How can I get an object from select element via AngularJS

I have select html element like this:

<select required="" ng-model="studentGroup">
<option value="" selected="">--select group--</option>
<option value="1">java 15-1</option>
<option value="2">java 15-2</option>
<option value="3">java 15-3</option>
</select>

I want to get an object - studentGroup: {groupId:'1', groupName:'java 15-1'} when first option is selected(for example), where groupId - 'value' attribute of selected option, groupName - 'text' attribute.

How can I do this using AngularJS?

UPDATE:

It was solved as below:

<select ng-options="group.groupName for group in ctrl.groupList track by group.groupId" ng-model="ctrl.student.studentGroup"></select>
Selected studentGroup object: {{ctrl.studentGroup}}

where ctrl - my controller with groupList Array with studentGroup objects; studentGroup - selected object as I wanted.

Upvotes: 1

Views: 1874

Answers (4)

Theo Itzaris
Theo Itzaris

Reputation: 4681

Hello I have made an example the uses a <select> element ,json array object to load values, custom directive that listens change events and calls controller function to give the selected object.

plunkr example: http://plnkr.co/edit/iCS0blQjceA4tIIb8bUV?p=preview

into html

{{selectedObj}}
<div class="col-xs-12 form-control"
         change-hall="filterHall(value)"
         items=items
         event-halls-list
         model='selectedObj'>

   </div>

custom directive(name it as you like)

.directive('eventHallsList', function($timeout, $log, $http, $compile) {
    return {
      restrict: 'AE',
      replace: true,
      scope: {
        changeHall: '&',
        items: '=',
        model: '='
      },
      templateUrl: 'mytemplate.tpl.html',
      link: function(scope, element, attrs) {
      }

    }
  });

enter image description here

Upvotes: 1

AshBringer
AshBringer

Reputation: 2673

How about that :

$scope.studentGroup = [
    { groupId: 1, groupName: 'java 15-1'},
    { groupId: 2, groupName: 'java 15-2'},
    { groupId: 3, groupName: 'java 15-3'},
    { groupId: 4, groupName: 'java 15-4'}
];

<select 
    ng-options="p.groupId + ' ' + p.groupName for p in studentGroup" ng-model="selectedPerson">
</select>

Demo

Upvotes: 1

Devendiran Kumar
Devendiran Kumar

Reputation: 223

This can be achieved with angular's ng-options directive. By declaring values for the select drop down in an array and iterating it with the help of ng-options directive

$scope.studentGroups = [{
  id: 1,
  groupName: 'java 15-1'
}, {
  id: 2,
  groupName: 'java 15-2'
}];


<select ng-options="studentGroup as studentGroup.groupName for studentGroup in studentGroups track by studentGroup.id" ng-model="selected"></select>

Upvotes: 1

lex82
lex82

Reputation: 11317

You can use the angular select directive together with ng-options. This way you can provide arbitrary objects as values.

Upvotes: 0

Related Questions