0

I am in need to do such thing

<select>
  <option ng-sth="firstMethodToBeCalled()">Option 1</option>
  <option ng-sth="secondMethodToBeCalled()">Option 2</option>
<select>

Is there any way to do this? I need this because i currently have this kind of code:

<select ng-model="someModel" ng-change="callThisFunction()">
  <option value="value1">Option 1</option>
  <option value="value2">Option 2</option>
  ...
  <option value="valueN">Option N</option>
</select>

And I want to add only two more options to this Select but calling different function. I can refactor it to call same wrapper function and determine which final function shall be called with some conditional logic but I am wondering if there is a possibility to assign different. I have been looking for this for some time and didn't come across any solution.

3
  • Can't you pass the ng-model value to the callThisFunction() and determine the logic to be called based on the value. Commented Sep 30, 2016 at 7:56
  • Yes I can. But I would have to refactor few controllers/services that rely on this model to maintain clean code. Sure I will if nothing else will come across. Commented Sep 30, 2016 at 7:57
  • Look this jsfiddle.net/81t6cbjw/483 Commented Sep 30, 2016 at 7:58

2 Answers 2

1

Unfortunately, i'm afraid you can't.

By the way, i would keep to have single function in ng-change and the put some logic inside it (and call your second function too from there), like this:

$scope.callThisFunction = function(){
   if(someModel == "baz")
      myFirstfunction();
   else
      mySecondFunction();
}

it's the cleanest solution in my opinion, and the most mantainable.

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

Comments

0

Yes ! there is a way you can achieve this.Create a functions object with keys as your selected option which is your ng-model and value as a function aligned to it and performa ny action in it.

In your JS

$scope.functions ={
    "value1":function(){
        console.log("function for option 1 called");
    },"value2":function(){
        console.log("function for option 2  called");
    }
};

In your HTML

<select ng-model="someModel" ng-change="functions[someModel]()">
  <option value="value1">Option 1</option>
  <option value="value2">Option 2</option>
  ...
  <option value="valueN">Option N</option>
</select>

Call the functions object in your ng-change by passing the your ng-model which is selected option which will invoke corresponding function.

Comments

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.