0

when I alert this I only get the last value of id. ican't findout where I'm going wrong

  $scope.addToList = function (products,qty) {
    if ($scope.order.length > 0) {
        for (var i = 0; i < $scope.order.length; i++) {
            $scope.Thx=$scope.order[i].id;
            }}};

   alert($scope.Thx);
2
  • 1
    What do you think $scope.Thx=$scope.order[i].id; is doing? Inside the loop it is resetting the value of $scope.Thx on every loop. Thus, when you alert after the loop, it will be the very last value. Commented May 22, 2018 at 11:58
  • $scope.Thx should be an array. Then append values to it with $scope.Thx.push( ... ) Commented May 22, 2018 at 11:58

2 Answers 2

3

Declare the $scope.Thx as an array first.

$scope.Thx = [];

$scope.addToList = function (products, qty) {
    if ($scope.order.length > 0) {
        for (var i = 0; i < $scope.order.length; i++) {
            $scope.Thx.push($scope.order[i].id);
        }
    }
};
Sign up to request clarification or add additional context in comments.

Comments

1

This line will overwrite the $scope.Thx for each iteration inside the loop.

$scope.Thx=$scope.order[i].id;

Now there are two ways to get the desired result. 1. If you want the separate alert for each item in the array then:

$scope.addToList = function (products,qty) {
if ($scope.order.length > 0) {
    for (var i = 0; i < $scope.order.length; i++) {
        $scope.Thx=$scope.order[i].id;
        alert($scope.Thx);
        }}};

2. If you want single alert for all the items. declare $scope.Thx as an array first.

$scope.Thx = [];
$scope.addToList = function (products, qty) {
if ($scope.order.length > 0) {
    for (var i = 0; i < $scope.order.length; i++) {
        $scope.Thx.push($scope.order[i].id);
    }
}
};
var tempVar="";
for(var i=0; i<$scope.Thx.length;i++)
{
    tempVar += $scope.Thx[0]+"\n";
}
alert(tempVar);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.