8

My problem is that for each select option I need to call a different function, not the same function.

I started with ng-click on each select option but quickly realized this doesn't work. I then read Angular's documentation on ng-options https://docs.angularjs.org/api/ng/directive/ngOptions

The documentation illustrates using ng-change but it is based on the fact that each select option gets the same function applied to it.

After thinking about this for a bit I ended up creating a function that gets called on ng-change. This function just determines which delegate to call.

$scope.determineAction = function() {
    var getDelegation = $injector.get($scope.selected.action);
    getDelegation.delegate();
  }

Plunker: http://plnkr.co/edit/2Str6OqmFDH3kKdiW6i5

I've created a solution to my problem but I want to know if this is the right approach? Am I missing something in ng-options that allows for many different function calls?

Harbinger
  • 594
  • 1
  • 8
  • 18

1 Answers1

3

TL;DR: Yes, you are doing the right thing.

Yes, you are doing the right thing. You're not missing some secret aspect of ng-options that allows you to specify something different for each item. In fact, doing this would defeat the purpose of ng-options. It's meant specifically for situations where the number of items you're dealing with are variable, but the actions that need to be executed on them are the same.

In your Plunker, you're demonstrating this exactly. You have a list of actions that is variable; it could have any number of actions to do. However, what you want to do with them is the same: when you select a new item, you want to run some action as specified by your backing scope. This is exactly what the controller is meant to do! As you found, all you need to do is write your function in such a way that it determines the current state of things and reacts accordingly. And all your view needs to do is make sure that it is setting up that state so that your controller can make sense of it.

You're doing all of this already so keep it up!

SethGunnells
  • 1,269
  • 1
  • 12
  • 19