John John - 7 months ago 15
Javascript Question

setting a method in the controller based on requirement

I am working on the

GalleryController
where I am trying to add a method called
setCurrent
that accepts a value and assigns it to
current
. If no value is passed in, I need to set the
current
to
0
.

Here is what I have written and it doesn't seems to be correct:

(function() {
var app = angular.module('gemStore', []);

app.controller('GalleryController', function(){
this.current = 0;

this.setCurrent = setCurrent(intValue){
if(intValue === null){

this.current = 0;
}
else {
this.current = intValue;
}
};

});

app.controller('StoreController', function(){
this.products = gems;
});

app.controller('TabController', function(){
this.tab = 1;

this.setTab = function(newValue){
this.tab = newValue;
};

this.isSet = function(tabName){
return this.tab === tabName;
};
});


Should I first set
this.current = intValue
as stated in the requirement?

Answer

If no value were passed in, then intValue would be undefined, not null. So your function body doesn't work.

Another huge problem here, which I can only hope is a typo, is that you have setCurrent where you should have function.

I don't understand the question at the end of your post, but this will behave as desired:

this.setCurrent = function (intValue) {
   if (!intValue) {
     this.current = 0;
   }
   else {
     this.current = intValue;
   }
};

If you really want to check whether an argument was passed in or not, then the only reliable way to do this is to check arguments.length:

this.setCurrent = function (intValue) {
   if (arguments.length === 0) {
     this.current = 0;
   }
   else {
     this.current = intValue;
   }
};

This seems pointless to me though. If the value is falsy, then it's clearly either 0 already or it's not a valid numeric value.