Nurul Alam Anik Nurul Alam Anik - 3 months ago 14
Javascript Question

Trying to create angular foreach with dynamic variable

I am trying to create a list of variable with id attached. I am using following code with foreach loop.

angular.forEach(str, function(value, key) {
console.log(key + ': ' + value.id);
//we found project id
//now attach it to dynamic variable
$http.get("http://abounde.com/portal/api/tasks/"+value.id).then(function(response) {
//create dynamic variable
if (key != null) {
$parse("project_"+value.id).assign($scope, value);
}
$scope.value = response.data.taskLists;
});

});


I want to have project_1, project_2, project_3 .... passed to scope.

What I am doing wrong?

Edit:

After looking at some suggestions tried something..

app.controller('portalController',function($scope, $http, $rootScope){
$scope.$on('$viewContentLoaded', function() {
$rootScope.backgroundImg="url(" + images[2].imgObj.src + ")"; //abt bg
$http.get("http://abounde.com/portal/api/projects").then(function(response) {
$scope.myData = response.data.projects;
var x=0;
var str = response.data.projects;
angular.forEach(str, function(value, key) {
console.log(key + ': ' + value.id);
//we found project id
//now attach it to dynamic variable
$scope.projects = [];
$http.get("http://abounde.com/portal/api/tasks/"+value.id).then(function(response) {
//create dynamic variable
$scope.projects.push(value.id) = response.data.tasklists;

});
//console.log($scope.projects);
});
});


});

//make a function which takes project id as parameter and returns tasks list
$scope.getTasksList = function(projectId)
{
$http.get("http://abounde.com/portal/api/tasks/"+projectId).then(function(response) {
$scope.myTasks = response.data.tasklists;
});
}

});


Following error

enter image description here

How do i access the dynamic variable on view? I am assuming I will need to use something like..


What is the actual way of accessing dynamic variable in angular?

Answer

No need to use $parse

Change it to $scope, and use proper object maniuplation.

$scope['project_'+v‌​alue.id] = value;

Or, so you can use the data in an array of dynamic values;

$scope.projects = [];
// inside your response
$scope.projects.push({
    _id : 'project_'+v‌​alue.id,
    value : value
});

HTML:

<div ng-repeat="project in projects">
    id: {{ project._id}}
    value: {{ project.value}}
</div>
Comments