简体   繁体   中英

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.

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>

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

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) {
      }

    }
  });

在此输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM