ryanh ryanh - 4 months ago 9
AngularJS Question

Assigning javascript variable to angularjs $scope.options

I am new to angularjs and have struggled with, what seems to be a simple task, and was hoping someone could help me. The following code is in my controller. I am dynamically generating the data that needs added to $scope.options.

This is what my data looks like:

[{ name: "a", id: 1 }, { name: "b", id: 2 }];


This works:

$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];


This doesn’t work:

var res = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.options = res;


Controller:

for (var i = 0; i < jsonArray.length; i++) {
if(i == (numberofitems-1)){

teststuff += "{name:\""+jsonArray[i]["pondpitname"]+"\", id:"+jsonArray[i]["id"]+"}";
}
else
{
teststuff += "{name:\""+jsonArray[i]["pondpitname"]+"\", id:"+jsonArray[i]["id"]+"}, ";
}


}

// teststuff looks like this [{ name: "a", id: 1 }, { name: "b", id: 2 }];
var res = "["+teststuff+"]";


$scope.options = res;

Answer

As @maddob mentioned you are working with string. If you want to convert json string into object, try angular.fromJson But if you want directly generate object, First i would recommend instead of for loop use angular.forEach (here is link https://docs.angularjs.org/api/ng/function/angular.forEach) and before init teststuff or res as array

var result = [];
angular.forEach(jsonArray, function(value) {
   result.push({id: value.id, name: value.pondpitname});
});
Comments