How does this validation.isElementInArray() in AngularJS works? - angularjs

Here is my code, where the if condition used that approach.
if( validation.isElementInArray($scope.inputBox, $scope.comments) )
{
$scope.error_msg = " ";
$scope.comments.push($scope.inputBox);
$scope.inputBox = '';
}
else
{
$scope.error_msg = "Name can't be Same";
}

validation.isElementInArray($scope.inputBox, $scope.comments) works same as you do
$scope.comments.indexOf($scope.inputBox) !== -1
Which means that the element $scope.inputBox exist in $scope.comments. Thus, looking at your condition you should be pushing the element in $scope.comments when $scope.inputBox do not exist in it. So, it should be,
if (!validation.isElementInArray($scope.inputBox, $scope.comments)){
$scope.error_msg = ' ';
$scope.comments.push($scope.inputBox);
$scope.inputBox = '';
}
else {
$scope.error_msg = 'Name can\'t be Same';
}

Related

Messenger Extensions Javascript SDK Error [duplicate]

I have some JavaScript code that gives this error:
Uncaught TypeError: Cannot read property 'value' of undefined
Here is my code:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
What does this error mean?
Seems like one of your values, with a property key of 'value' is undefined. Test that i1, i2and __i are defined before executing the if statements:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if(i1 && i2 && __i.user && __i.pass)
{
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}
Either document.getElementById('i1'), document.getElementById('i2'), or document.getElementsByName("username")[0] is returning no element. Check, that all elements exist.
Try this, It always works, and you will get NO TypeError:
try{
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}catch(e){
if(e){
// If fails, Do something else
}
}
First, you should make sure that document.getElementsByName("username")[0] actually returns an object and not "undefined". You can simply check like
if (typeof document.getElementsByName("username")[0] != 'undefined')
Similarly for the other element password.
The posts here help me a lot on my way to find a solution for the Uncaught TypeError: Cannot read property 'value' of undefined issue.
There are already here many answers which are correct, but what we don't have here is the combination for 2 answers that i think resolve this issue completely.
function myFunction(field, data){
if (typeof document.getElementsByName("+field+")[0] != 'undefined'){
document.getElementsByName("+field+")[0].value=data;
}
}
The difference is that you make a check(if a property is defined or not) and if the check is true then you can try to assign it a value.
You can just create a function to check if the variable exists, else will return a default value :
function isSet(element, defaultVal){
if(typeof element != 'undefined'){
return element;
}
console.log('one missing element');
return defaultVal;
}
And use it in a variable check:
var variable = isSet(variable, 'Default value');
You code looks like automatically generated from other code - you should check that html elements with id=i1 and i2 and name=username and password exists before processing them.

how to check a value in array object angularjs

i have this array object:
$scope.datas.labels=['10','20','30']
and also i have a function return an array object like this:
response.labels=['10','20','30','50','100','80']
i created a function which recieve the last result..but what i want is to check if a value in response.labels exists in the $scope.datas.labels i dont want to insert it..to avoid duplicated data in $scope.datas.labels, how i can do that??
i tried this but i didnt work:
$scope.concatToData=function (response) {
if($scope.datas.labels=='') {
$scope.datas.labels = $scope.datas.labels.concat(response.labels);
}else {
var i;
for (i = 0; i < $scope.datas.labels.length; i++) {
alert('qa' + JSON.stringify($scope.datas.labels));
alert('res' + JSON.stringify(response.labels));
if ($scope.datas.labels[i] !== response.labels[i]) {
$scope.datas.labels = $scope.datas.labels.concat(response.labels[i]);
} else {
break;
}
}
}
$scope.datas.datasets = $scope.datas.datasets.concat(response.datasets);
}
Try this it will work as per your expectation and requirement.
var arr1=['10','20','30'];
var arr2=['10','20','30','50','100','80'];
for (var i in arr2) {
if(arr2[i] != arr1[i]) {
arr1.push(arr2[i]);
}
}
document.getElementById('result').innerHTML = arr1;
#result {
font-weight:bold;
}
<div id="result"></div>
Take a look at the lodash library, you'll find it useful, and this will be useful for you too:
let common = _.intersection($scope.datas.labels, response.labels);
if (_.size(common) && _.includes(common, 'myValue')) {
// You have a winner;
// This item (myValue) is in both;
} else {
}
Hope that helps.
You can also try that:
var response = ['foo', 'fabio'];
var labels = ['foo'];
var result = response.filter((value) => {
return labels.filter((rs) => {
return rs == value;
}).length == 0;
});
It will return only the data that does not exists on $scope.datas.labels.

break a forEach with angularJS

I need some help. I have 2 loops to traverse two lists of records . The thing is that at some point should put a break or something, because the last loop crushes the value I'm looking for.
This is my code
for (var i in $scope.users) {
for (var j in $scope.states) {
if ($scope.users[i].id === $scope.states[j].user) {
if ($scope.states[j].estado === 'totallyBussy') {
$scope.users[i].estado= 'Not available';
} else if ($scope.states[j].estado === 'partlyBussy') {
$scope.users[i].estado= 'Maybe available';
}
}
else {
$scope.users[i].estado= 'Available';
}
}
}
Where user 4 and user 5 should be 'Maybe available' and 'Not available', but with this code, I'm getting 'Available for user 0, 1, 2, 3, and the last one. And the last one is crushes with else.
I hope I explained well.
Thanks so much
You can use the break keyword, which will end the loop when executed.
One side note: you don't want to use for (var i in array) {} since you may iterate through Array properties (and have i take unexpected values).
I updated your code with a more reliable iteration.
for (var i = 0, il = $scope.users.length; i < il; i++) {
var user = $scope.users[i];
for (var j = 0, jl = $scope.states.length; j < jl; j ++) {
var state = $scope.states[j];
if (user.id === state.user) {
if (state.estado === 'totallyBussy') {
user.estado = 'Not available';
} else if (state.estado === 'partlyBussy') {
user.estado = 'Maybe available';
}
// Go to the next user (break the "states" loop)
break;
} else {
user.estado = 'Available';
}
}
}
EDIT: If $scope.users and $scope.states are not Arrays but actually Objects (which would seem strange to me but anyway), you can keep for (var i in object) {} but you have to add a check: if (object.hasOwnProperty(i)) {} in the loop.
you can add a flag which will become true when you got your desired value.
something like
var gotValue = false;
for (var i in $scope.users) {
if(!gotValue)
{
for (var j in $scope.states) {
if ($scope.users[i].id === $scope.states[j].user) {
if ($scope.states[j].estado === 'totallyBussy') {
$scope.users[i].estado= 'Not available';
gotValue = true;
} else if ($scope.states[j].estado === 'partlyBussy') {
$scope.users[i].estado= 'Maybe available';
gotValue = true;
}
}
else {
$scope.users[i].estado= 'Available';
gotValue = true;
}
}
}
}
In AngularJS, there is no break for loops,etc., so one has to go with logic manually.
A similar case has been demonstrated here.
Here, I have created a variable f, which has been set to false initially. On forEach loop, based on a condition, it is made to true, further which it works as break.
Please find the code below:
HTML:
<div ng-app="app" ng-controller="test"></div>
JS:
var app = angular.module('app',[]);
app.controller ('test', function ($scope){
var f = false;
angular.forEach([1,2,3,4,5], function(v,k){
if(k > 2){
f = true;
}
if(!f) {
document.write('value = ' + v + ' <br>');
}
});
});

screeps.com: simple script not working, issue with bi-dimensional array

I get the following error from the console: "TypeError: Cannot read property '0' of undefined", it has something to do with the array but I cannot find the mistake.
module.exports =
{
create_creeps: function()
{
var aHarvester = [[TOUGH,TOUGH, MOVE, CARRY, WORK, MOVE]["harvester"]];
Spawn.prototype.createMyCreep = function(aCreep,sRole) {
if (!Game.spawns.Spawn1.spawning){
var nameCount = 0;
var name = null;
while(name == null)
{
nameCount++;
var tryName = sRole + nameCount;
if(Game.creeps[tryName] == undefined)
name = tryName;
}
var dbg= this.canCreateCreep(aCreep, name);
if(dbg == OK) {
console.log("Creating creep " + sRole);
return this.createCreep(aCreep , name,{ role:sRole });
} else {
console.log("error "+dbg+" "+sRole);
}
}
};
Game.spawns.Spawn1.createMyCreep(aHarvester[0],aHarvester[1][0]);
};
}
Please separate arrays with a comma
So
[[TOUGH,TOUGH, MOVE, CARRY, WORK, MOVE]["harvester"]]
Should be
[[TOUGH,TOUGH, MOVE, CARRY, WORK, MOVE],["harvester"]]

AS3/Flash: check if a variable value exists in an array II

Some days ago, Cherniv gave to me this tip:
var name = "Nora";
var names:Array = ["Mary", "Porter", "Nora", "Flint", "Elsa", "Clair",...];
if( names.indexOf( name ) > -1 )
{
// Success
}
Now, I can't check the existence of "Nora" in this array:
var names:Array = [{label:"Mary"}, {label:"Porter"},{label:"Nora"}, ...];
I'll appreciate any help.
Cheers.
UPDATE:
Now it's working. I did use:
for each (var obj:Object in list)
{
if (obj.label == compList.text)
{
updateList = 1;
break;//stops the loop;
}
}
if (updateList == 1)
{
removeCompany();
}
else
{
var nativeAlert:NativeAlert = new NativeAlert();
nativeAlert.alert("You can't update the name!");
}
Is this OK or is an ugly solution?
Thanks
for each( var obj : Object in names )
{
if( obj.label == "Nora" )
{
// Success;
break;//stops the loop;
}
}
I can make it more complex/flexible if you wish.

Resources