ngShow/ngHide using a function - javascript

I have a button that I want to hide when the array $scope.game.players.players contains specific value.
button(ng-click="", ng-hide="ImPlaying()") Play
The function ImPlaying() checks the condition and return a boolean
$scope.ImPlaying = function(){
$scope.game.players.playerExist($scope.user.socketID, function(exist){
console.log(exist);
return exist;
});
}
exist change value but the button is always shown
But when I replace the function $scope.game.players.playerExist() by its code everything works as expected.
$scope.ImPlaying = function(){
for (var i = 0; i < $scope.game.players.players.length; i++) {
if($scope.game.players.players[i]){
if($scope.game.players.players[i].socketID == $scope.user.socketID){
return true;
}
}
};
return false;
}
What's wrong with the first function ?

You're missing return statement in ImPlaying function
$scope.ImPlaying = function(){
return $scope.game.players.playerExist($scope.user.socketID, function(exist){
console.log(exist);
return exist;
});
}

Related

jquery return true or false according custom function

I want to bind following code in custom function and return true if field has value and false if field is empty. Validating with only one variable, it was easy. But when validating two array I think it can be possible only custom function. I think code becomes unnecessarily lengthy as well because of lack of custom function. Please guide me.
$(document).on('click', '.subadd', function(){
//I want to bind this code in function
var sid = [];
$('input[name="sid[]"]').each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
};
if($(this).val()){
$(this).removeClass('border1red');
sid.push(this.value);
}
});
var title = [];
$('input[name="title[]"]').each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
};
if($(this).val()){
$(this).removeClass('border1red');
title.push(this.value);
}
});
//function
//if function return true
if(sid.length && title.length){
$('table#menutable tr:last').after("<tr>.....</tr>");
};
});
First you can shorten your each loop.
if(!$(this).val()){
$(this).addClass('border1red');
return false;
} else {
$(this).removeClass('border1red');
title.push(this.value);
}
You can also make a function for that, with the selector and the array as parameters.
$.validate = function(selector, array) {
$(selector).each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
} else {
$(this).removeClass('border1red');
array.push(this.value);
}
}
}
In the end, the main section of the code would look like this:
var sid = [];
var title = [];
$.validate('input[name="sid[]"]', sid);
$.validate('input[name="title[]"]', title);
if(sid.length && title.length){
$('table#menutable tr:last').after("<tr>.....</tr>");
};

How do I write a jasmine expectation that a function has returned when an input parameter is null?

I have the following javascript function:
function(fieldObject, value) {
if (!value) {
return;
}
// call some other functions
}
Is it possible to write an expectation that the function gets returned in the if statement without writing multiple expectations that all the other functions after the if statement are not called?
That's a pretty interesting question:
I'm not 100% sure if there is a way to achieve what you are seeking, however I have used this trick to verify the state of early return (like in your case)
Here us how I used it-
Make your void methods return false to exit the processing. You may
not use this return value in the code but you can sure test it
efficiently.
If your method is is expected to return a value yet it has an early return/break, you could still break it with return false.
Code sample to illustrate the above scenarios:
var testObj = {
voidLikeFunction : function(arg1){
if(!arg1){
return false;
} else {
console.log('Executes void like function..');
this.callAFunction();
this.callAnotherFunction();
this.callYetAnotherFunction();
}
},
callAFunction : function(){
console.log('callAFunction()');
},
callAnotherFunction : function(){
console.log('callAnotherFunction()');
},
callYetAnotherFunction : function(){
console.log('callYetAnotherFunction()');
},
expectedToReturnInt : function(arg1){
if(!arg1){
return false
} else {
var sum =0;
for(int i=0; i<10; i++){
sum += i;
}
return sum;
}
}
};
describe('testVoidLikeFunc', function(){
it('testEarlyReturn', function(){
var val = testObj.voidLikeFunction();
expect(val).toBe(false);
});
it('testLateReturn', function(){
spyOn(testObj, 'callAFunction').and.callThrough();
spyOn(testObj, 'callAnotherFunction').and.callThrough();
spyOn(testObj, 'callYetAnotherFunction').and.callThrough();
var dummyParam = true;
testObj.voidLikeFunction(dummyParam);
expect(testObj.callAFunction).toHaveBeenCalled();
expect(testObj.callAnotherFunction).toHaveBeenCalled();
expect(testObj.callYetAnotherFunction).toHaveBeenCalled();
});
});
describe('testExpectedToReturnInt', function(){
it('testEarlyReturn', function(){
var val = testObj.expectedToReturnInt();
expect(val).toBe(false);
});
it('testLateReturn', function(){
var dummyParam = true;
var val = testObj.expectedToReturnInt(dummyParam);
expect(val).toEqual(45);
});
});

Return false from Function within function - Javascript Form Validation

I made a function which validates a form and works fine but I now want to break it down into 3 separate functions.
I now have a function which is called by the form being submitted which declares some arrays and runs the three functions. When it was all one big function the various if statements that found errors would return false; which would then go back to the form and stop it sending.
However now that I've got functions within a function I can't figure out how to get that message 'false' back to the form.
Below is the function called by the form submit button followed by the main function it calls.
I tried creating an empty variable which is returned instead of false which is then is assigned the value false by the validateSignup function but it didn't work.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
passMatch();
genderCountryCheck()
}
function validateText(formNumber, numberElements, errorSpansArrayName, regexErrorArrayName, regexArrayName)
{
for (x = 0; x<numberElements; x++)
{
var spanName = errorSpansArrayName[x];
var textError = document.getElementById(spanName);
var y=document.forms[formNumber].elements[x];
if (!y.value)
{
errorMessage(0,spanName,x);
return false;
}
if(!regexArrayName[x].test(y.value)){
textError.innerHTML = regexErrorArrayName[x];
return false;
}
}
UPDATE:
Thanks for your responses. I have found a solution that seems to work for me.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
var returnValidateText=validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
var returnPassMatch = passMatch();
var returnGenderCountry = genderCountryCheck();
if (returnValidateText || returnPassMatch || returnGenderCountry === false)
{
return false;
}
else{
return true;
}
}
If you call the function it returns a value
var formIsValid = function validateText(....)
should do the trick.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
var formIsValid = false;
formIsValid = validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
formIsValid = passMatch();
formIsValid = genderCountryCheck()
}
One way is to just check the individual function returns directly and return based on that
if (!validateText(0,6,errorSpansArray, regexErrorArray, regexArray)) {
return false;
}
if (!passMatch()) {
return false;
}
if (!genderCountryCheck()) {
return false;
}
Although it's shorter to use a single conditional
return
validateText(0,6,errorSpansArray, regexErrorArray, regexArray) &&
passMatch() &&
genderCountryCheck();
In javascript return false means false will be returned as value where the method is called. So you need something like
If(validateText()){
return true;
}
And similarly rest of the code.

Unable to return value from a function

I want to return value from the function which contains an anonymous function.
function getSingleCheckedItemId() {
return $(".data-table-chk-item").each(function() {
if ($(this).is(":checked")) {
var value = $(this).attr("value");
return value;
}
});
}
In this case it returns me the array of all checkboxes. If I remove the first return, it won't return a value but undefined.
So how do I return the value from getSingleCheckedItemId()?
.each always returns the jQuery object containing all elements that you iterated over so:
function getSingleCheckedItemId() {
var ret;
$(".data-table-chk-item").each(function() {
if ($(this).is(":checked")) {
ret = $(this).attr("value");
return false; //breaks out of .each
}
});
return ret;
}
Also, this.value is usually a better option than $(this).attr('value') in case you're dealing with form inputs - seems like you have radio/checkbox inputs due to their checked property. Also, this.checked returns a boolean so there's no need for $(this).is(':checked') either.
I believe your logic can be simplified to:
function getSingleCheckedItemId() {
return $(".data-table-chk-item:checked").val();
}
This way .val() will return the value of the first :checked item or undefined if no elements are matched by the selector, which does the same as the loop above.
You can do it:
function getSingelCheckedItemId() {
var elements = $(".data-table-chk-item:checked");
return (elements.length > 0) ? $(elements[0]).val() : undefined;
}
I would do it like this
function getSingleCheckedItemId() {
var ret;
$(".data-table-chk-item").each(function() {
if ($(this).is(":checked")) {
ret = $(this).attr("value");
}
});
return ret;
}

Javascript array indexOf returns undefined

When calling my function checkIss(), issFullArray.indexOf(issToCheck) always returns undefined. I've run a .length, output the contents of issFullArray, I can't figure out why it's not working- the array looks fine to me. As you can see below, I've tried explicitly setting issArray as an array and copying the array returned by my getIssList()
function updateIss() {
var issArray = [];
var currService = current.u_business_service;
var currIss = current.u_is_service;
issArray = getIssList(currService).slice(); //getIssList() returns an arry
if (checkIss(issArray, currIss) === false) {
//do stuff
}
}
function checkIss(issFullArray, issToCheck) {
if (issFullArray.indexOf(issToCheck) < 0) {
return false;
} else {
return true;
}
}
Easiest to just loop through the array and compare each value and return true if there is a match otherwise return false. Not much more code and works for all browsers.
function checkIss(issFullArray, issToCheck) {
for(i=0; i<issFullArray.length; i++) {
if(issFullArray[i]==issToCheck) {
return true;
}
}
return false;
}

Categories