4

How to call a function in the case given below?

<select class="dropdown">
    <option ng-repeat="group in myGroups" ng-model="group.Name" ng-change="myFunction(group.Id)">{{group.Name}}</option>
</select>
  • ng-click won't work
  • ng-model is needed if you want to use ng-change (I don't need ng-model in this case otherwise)
  • ng-change doesn't seem to call a function as well
  • I know I could probably just use ng-model and $watch, but since I don't think I can really use ng-model in this case I am a bit confused

So, how can I call a function inside ng-repeat select? (its not ng-select as you probably noticed)

1 Answer 1

11

Well, the option itself does not change.

What changes is the value of the select element.

So, try this:

<select ng-model="selectedGroup" ng-change="yourFunction()">
   <option ng-repeat="group in myGroups">{{group.name}}</option>
</select>

with a yourFunction on the current scopelike this:

scope.yourFunction = function() {
   console.log(scope.selectedGroup);
};

I also strongly suggest you have a look at ngOptions here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I was somehow reluctant to ngOptions since it all seemed a bit hard to grasp, but now I see it's handy as it can be. I like that you answered my question directly and also pointed out that ngOptions would probably be a better solution.
jsfiddle.net/YGf7d/2 is an example of ng-options being used with the ng-model on the select element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.