zubhav
zubhav

Reputation: 1559

Using ng-options with ng-changed in select form input

I'm trying to create a select widget using Angular's ng-options. I have this so far:

<select id="id_question" name="question" ng-model="post.Question"
    ng-options="question.id as question.title for question in questions"
    ng-change="updateFields(post.Question)" required>
</select>

I need an object passed through as a parameter to the 'updateFields' method. However, due to the ng-options using the 'id', this is not possible.

How do I retain using id as the value in the select widget but also have the ability to pass the 'question' object as a parameter in ng-change?

Upvotes: 0

Views: 51

Answers (2)

Aravind
Aravind

Reputation: 41571

When ever you use ng-model for a select element you need not pass the selected object as a event parameter in ng-change.

Have a look at the below code

$scope.updateFields=function(){
      console.log($scope.selectedQuestion);
    }

Your HTML must be as

<select name="question" ng-model="selectedQuestion"
    ng-options="question as question.title for question in questions"
    ng-change="updateFields()" required>

LIVE DEMO

Assumed json

$scope.questions=[
    {title:'A',id:1},
    {title:'Abcdef',id:4}];

Upvotes: 1

nishant agrawal
nishant agrawal

Reputation: 471

There is no way to pass complete object to your function if you are using ng-options. Instead what you can do is set your ng-model to some other property and use that property to assign value to your post.Question variable.

<select name="question" ng-model="selectedValue"
        ng-options="question as question.title for question in questions"
        ng-change="updateFields(selectedValue)" required>
</select>

in JS

    $scope.updateFields = function(question) {

       $scope.id = $scope.selectedvalue.id;
        console.log(question);
  }

Please have a look at plunker

Upvotes: 1

Related Questions