Gururaj Bhandarkar Gururaj Bhandarkar - 3 months ago 14
AngularJS Question

Array index in AngularJS

$scope.ptArray={m1 : $scope.somevalue1,
m2 : $scope.somevalue2,
m3 : $scope.somevalue3};
$scope.errMsg={m1 : 'msg1',
m2 : 'msg2',
m3 : 'msg3'};
if($scope.ptArray.this==""){
alert($scope.errMsg.this);
}


'this' doesn't work here. If I use m1, m2 or m3 instead of 'this' it will work, but only for that variable. What to use in the place of this

Answer

You can do something like this:

Get all the keys that have an empty String as a value:

var empty = [];
Object.keys($scope.ptArray).forEach((k) => {if(ptArray[k] == ""){empty.push(k);}});

Create an alert with the messages for all those keys:

var msg = "";
empty.forEach((k) => {msg+=$scope.errMsg[k]+"\n"});
if(msg.length > 0){
    alert(msg);
}

or do all that at once in a single loop:

var msg = "":
Object.keys($scope.ptArray).forEach((k) => 
      {
        if(ptArray[k] == ""){
            msg += $scope.errMsg[k]+"\n";
        }
      });
if(msg.length > 0){
    alert(msg);
}
Comments