0

Edit: This post Is there a better way to do optional function parameters in Javascript? provides an answer to this question.

This is my controller:

.controller("NavTabController", ['TabService', function(TabService) {
        var self = this;

        self.switchTab = function(currentTab, dropDown) {
            TabService.switchTab(currentTab, dropDown);
        }
}])

and this is the factory:

.factory("TabService", [function() {
    var tab = "home";
    return {
        switchTab: function(currentTab, dropDown) {
            tab = currentTab;
        }
    }
}])

In my HTML, I have this:

<a href="#" ng-click="ctrl.switchTab('home')">Home</a>
<a href="#" ng-click="ctrl.switchTab('home', 'middle')">Optional</a>

As you can see, I want dropDown to be optional because sometimes it is not provided.

With that said, what is the recommended way to have an optional parameter for an AngularJS function?

Community
  • 1
  • 1
SilentDev
  • 20,997
  • 28
  • 111
  • 214
  • 1
    You have a typo ~ `dropDown` vs `dropDrown` – Phil Aug 06 '15 at 04:33
  • 1
    @Phil you are right, that is what was causing the issue. Turns out, AngularJS automatically makes the parameter "undefined" if it isn't provided. AngularJS does not throw an error when I do not provide a parameter. I'm assuming the recommended way is to do "if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }" because that is the answer for the other SO question. So I'll mark this as a duplicate. – SilentDev Aug 06 '15 at 04:45

1 Answers1

0

Try using arguments.length === 2

duellsy
  • 8,497
  • 2
  • 36
  • 60
Mark Robson
  • 1,298
  • 3
  • 15
  • 40