Variable on scope doesn't keep the value changed in a function - javascript

I have a controller which initializes my value as such:
$scope.showThing=true;
I toggle the value with ng-click like
ng-click="showThing=!showThing"
which works ok but then if I try using the same value in a function inside the controller it behaves irrational, to say the least.
Something as simple as alerting the value in an interval function only gets the right value the first time it iterates after changing the value, sometimes not even that.
Since it's something so trivial I wouldn't want to create a factory for this alone, so I hope there's someone who can tell me what am I doing wrong here.

Your question is not straightforward, can you post the code. Here is hoisting issue.
var a = 10;
console.log("value of 'a' before hoisting: "+a);
(function(){
console.log("value of 'a' after hoisting: "+a);
var a;
})();
Result:
value of 'a' before hoisting: 10
value of 'a' after hoisting: undefined

This may be, because interval is initiated once, and then only is returning the same value over and over. Try something similar to this, with a getter style function involved:
$scope.showThing=true;
var getShowThing = function() {
return $scope.showThing;
};
$scope.displayTr=function(){
alert(getShowThing());
};
$interval(function() {
//get data from a factory .then(function(response) {
if (response.status === 200) {
$scope.info = response.data;
} else {
console.log('Error occured' + response.status);
}
});
$scope.displayTr();
}, 5000);
Hope this helps.

Related

What does Return do in here?

I have problem with 'return' means in this code.
1.
function func4() {
var str = "function works.";
console.log(str);
}
func4();
2.
function func4() {
var str = "function works.";
return str;
}
var value = func4();
console.log(value);
Both of them, their result is 'function works.'.
I know that return used for exit function but I'm still confuse when I have to use return exactly.
Sorry about my super basic question :(
As far as I understand 'return' assigns value to a function and returns it, so you're displaying function's value. In the first case you are just simply invoking a function to display a string.
Let's analize this two scenarios:
You have a function that initialize a variable with a predefinided value, and then, you log the value. Then, outside the function you execute it
You have the same variable but with the difference that instead of loggin the value inside the function, you returned it from it. So you can initialize the funcion and store the value on another variable var value = func4();.
Let me try to explain it with some requirements.
I want a function which returns me some data instead of passing a variable and updating the variable in function.
You call a function and it is always best to test negative scenarios first. So in case of negative scenario you can return it from there it self.
In your second case if you see you are getting a value from that function and then printing it. Same thing you can not do using first function.
Always there are workarounds for everything. In the end it depends on your need and what is best suited for that situation.
Both of those functions don't equal the same thing, but they do log the same string.
func4() in #1 is equal to undefined, because it returns nothing.
func4() in #2 returns (gives back) the value "function works.", a string, which is then given to console.log outside of the function.
function func1() {
var str = "function works.";
// console.log(str);
}
func1();
function func2() {
var str = "function works.";
return str;
}
// console.log(func2());
console.log(func1() === undefined);
console.log(func2() === 'function works.');
If you want to use the func4() value for further calculations without calling it again, then you would return {value}.
For e.g
function func4(userInput) {
return userInput % 2 == 0;
}
var response = func4(userInput);
if(response == true) {
console.log('user entered an even number');
} else {
console.log('user entered a odd number');
}
// from here you can use the value of response n times without calling the function again.
Whereas, if you don't return then you will have to call the function x number of times whenever you want to re-user the response of it.
function func4(){
var str = "function works.";
return str;
}
var value = func4();
console.log(value);
//here return means you are returning the value of variable 'str'.
You can find the details here.
https://learn.microsoft.com/en-us/cpp/c-language/return-statement-c?view=vs-2019#:~:text=A%20return%20statement%20ends%20the,value%20to%20the%20calling%20function

Javascript global variable undeclared problem

In the mentioned sample code I'm trying to get a value for val variable. I declared it with global scope. And add some console log to verify values. But inside of the function it assign value without problem. But out of the function val is undeclared. why is that?
$.validator.addMethod("serialverify", function(){
var val;
$("#serialno").keyup(function(){
serial().done(function(data){
console.log('final = ' + data);
val = data;
console.log(val);
});
}); console.log(val);
return val;
}, "Please enter valid serial code");
There is a fundamental problem in your code. The assignment is taking place in a callback function, which means it'll only execute when the action keyup is made.
However, the statement return val is happening synchronously.
Suggestion -
You can wrap it in a promise of some sort and resolve it when done is executed. Something on the lines of -
......done( function(data) { ..... resolve(val); })
or declare var val; as global that is outside, the addMethod function

Javascript SessionStorage Checking Before Running a Function

I have a function that I'm calling. Called getStatus(). But this function requires there to be a defined SessionStorage variable that could be present. If the variable is present then I want to go ahead and execute the getJob() function. If it's not present I want to try to define the SessionStorage variable and then execute the getJob() function.
Like this:
function getStatus()
{
if (sessionGet("jwt") != null)
{
getJob(document.getElementById('job').value, document.getElementById('id').value);
}
else
{
var myValue = '{{ myValue }}';
console.log("Token is missing, acquiring another one!");
var nextToken = setTimeout(function(){ getSessionToken(myValue); }, 5000);
console.log("Reissued token issued is");
console.log(nextToken);
getJob(document.getElementById('job').value, document.getElementById('id').value);
}
}
And here is the function that reads the SessionStorage variable:
function sessionGet(key) {
let stringValue = window.sessionStorage.getItem(key)
if (stringValue !== null) {
let value = JSON.parse(stringValue)
let expirationDate = new Date(value.expirationDate)
if (expirationDate > new Date()) {
return value.value
} else {
window.sessionStorage.removeItem(key)
}
}
return null
}
When I look at the Chrome console I see the SessionStorage variable being written, but the getJob() function that reads the variable doesn't see it. If I retry then the getJob() function is able to read it. My thought is that the getJob() function is firing before the variable has been written. That's why I tried the setTimeout() in there.
Any suggestions?
As ztadic91 pointed out, I needed to wrap the setTimeout around the getJob() function call, since it needed to wait for the SessionStorage variable to be created. After doing that things tested out fine. Appreciate the quick assist!

angularjs : update value of a variable After external timeout function call

I have a controller and a factory. A function(myfunc) inside the factory(searchFactory) is called by ng-click of a button. after which I call a function(waitfunction) which is outside the conntroller. In that function timeout of 2 sec is used and then a value is changed and returned to the controller. How can I make sure that the value is updated in the controller after 2 sec. JSfiddle : http://jsfiddle.net/zohairzohair4/cRr9K/1334/
var search_name
var angularjsapp = angular.module('graphApp', ['ngAnimate', 'ui.bootstrap']);
angularjsapp.factory('searchFactory', function() {
//return $resource('friends.json');
return{
myfunc:function(search_name){
console.log('ok')
keyword_type = 1
loading_value = waitfunction(search_name)
console.log(loading_value)
return loading_value
}
}
});
angularjsapp.controller('AccordionDemoCtrl', function($scope,searchFactory) {
$scope.count = 0;
$scope.namesPerPage = 10
$scope.currentPage = 1;
$scope.searchFactory = searchFactory.myfunc
});
function waitfunction(search_name){
value = 0
window.setTimeout(function () {
value = 1;
}, 2000);
return value
};
Using the setTimeout function will bypass angular's dirty checking. If you want to use async functionality outside of angulars dirty-checking, you need to trigger angular to do the dirty checking again. You can do that by calling $scope.$apply(); or wrap your async call with a function like this:
$scope.$apply(function() {
...
});
For your specific need - angular already have a number of async methods to replace the default javascript ones and i'd suggest you use that instead of javascripts timeout:
$timeout(function () {
value = 1;
}, 2000);
You can read more about $timeout here: https://docs.angularjs.org/api/ng/service/$timeout
Your waitfunction doesn't seem to be doing what you want it to do. It will return the value long before the timeout changes it. This happens because you're just referencing a simple value. If you pass an object and modify that objects property, then you can achieve what you're trying to do:
function waitfunction(search_name){
var obj = { value: 0 };
$timeout(function () {
obj.value = 1;
}, 2000);
return obj;
};
You then need to bind to the returning objects .value property instead.
I see your plunker and there is a lot of work to be done. It doesn't seem like you're binding the resulting object to anything. I think this post helps to solve atleast the async problem associated with calling setTimeout and the problem of binding to simple values.
You need to use $timeout
$timeout(function() {
value=1;
}, 2000);

Why does this JavaScript function always returns 'undefined' – and how to fix that?

I'm using phonegap with application preferences plugin and trying to make a helper function to get a value from it. However the function is not returning a correct value. I know this has to do with asynchronous thingy but unfortunately I don't know how to fix it. (I've tried to search help here, and found little, and tried to implement it in helper method)
What I want to achieve is:
function populateList() {
var a = 1;
var number = getSettingFromApplicationPreferences('number');
// number is always undefined
var letter = getSettingFromApplicationPreferences('letter');
// letter is always undefined
number = (number) ? number : 1;
letter = (letter) ? letter : 'b';
// Here I'll do some DOM manipulation and use 'number' and 'letter' on it, and
// define new variables based on 'number' and 'letter'
}
here's the helper function that I need help with:
function getSettingFromApplicationPreferences(setting) {
var x = (function () {
window.plugins.applicationPreferences.get(
// setting
setting,
// success callback
function(returnValue) {
console.log(setting + ': ' + returnValue);
return returnValue;
},
// error callback
function(error) {
alert("Failed to get a setting: " + error);
return false;
}
);
})();
return x;
}
Question
How is it possible to return the 'returnValue' from application preferences with that helper function?
The problem is, your callback doesn't actually set a value for x. So, you're going to have some other way to do whatever you're doing, because return values will not work.
You are using an asynchronous function incorrectly, you cannot assign like you are because the function hasn't returned yet and so you get an undefined. You need to use a callback function instead.
That means that inside the success function you would do whatever you need to do with the "returnValue".

Categories