Calling different functions in ng-change

It’s been a while I’ve written a blog post, so what was I doing ? Yea you can say I’m lazy (agreed :p) but on brighter side I was actively answering questions related to Angular Js in StackoverFlow .Hmm so in this quest of answering random things I came across a strange question  , at first I thought it’s a silly question but later while I was thinking more on it I’ve realized may be this is a quite reasonable question to ask and I said to myself lets answer this 😉

What is the problem statement ?

Let’s say you have a need of calling a function depending on the value selected / changed by the user to perform different actions.We usually do it by calling our function in ng-change but what if we want to call different functions depending on the option selected in he drop down ? How do we do that ?

Solution approach

There are two different ways to approach this problem

  1. if – else if – else strategy 

This is the most common approach which everyone will try to implement and there is nothing wrong in that.This way provides a better code maintainability on pro side but the con is we have to deal with lot of conditions to perform the logic which makes your code look like a pasta :p

Let’s take an example, I have a drop down like below in my HTML

<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>

In my  JS  what I would do is depending on the selected option value I will call a different function to perform.

$scope.callThisFunction = function(){
   if(someModel == "value1"){
   }else if (someModel =="value2"){

2. Object oriented approach 

This one is something fascinating and a cleaner approach where you can define which function to be called on which selected value by a key value pair object.

Let’s create a $scope.functions {} object in our JS

$scope.functions ={
        console.log("function for option 1 called");
        console.log("function for option 2  called");

In our HTML lets invoke this object in our ng-change by sending our ng-model value as key.

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

In this approach we have avoided lot’s of unnecessary conditions and a cleaner code for readability no extra wrapper function to invoke other functions.

Hope this post gives you a different perspective on how to call multiple / different function in a better way and how to implement this with ng-change and other angular directives.

Cheers !! 🙂 Keep coding  Keep  cheering !