1

I wrote an $http.get function to extract data stored in a database.

I would like to use the database data in a dropdown function in AngularJS. Now this means that I have to create a new $scope JSON data variable and store the actual database data in it just so I can access it in my HTML page.

<select popover="Choose your input drug, type to filter list of drugs" data-ng-model="currentData"
    data-ng-options="name for name in ourDataName" style="width:300px;" convert-to-number >
</select>

ourDataName in data-ng-options is the variable I defined inside the controller as $scope.ourDataName, and it is supposed to have all the drug names inside it. It is possible for me to do what is written inside the get function below; however, the problem is that there are over 100 drug names:

$http.get(URL).success(function (data) {  //Note URL is where I stored my database. I did not put it for privacy reasons
    $scope.ourDataName = 
        [
            data[1].drug_name,
            data[2].drug_name,
            data[3].drug_name
        ]   
});

I tried to put a for loop over the JSON data as such:

for(var i=0; i<100;i++)
{
    $scope.ourDataName = 
    [
        data[i].drug_name
    ]   
}

The problem is it ended up showing the 100th drug name only since it shows what the loop ends at.

I am out of solutions. Is there any way to loop through the database and store them in a new variable without having to go over each as I did at first?

0

2 Answers 2

3

You don't need to create another data set for dropdown.

Use data directly which http get return.

Try like this

Controller

$http.get(URL).success(function (data) {        //Note URL is where I stored my database. I did not put it for privacy reasons
   $scope.ourDataName=data;
});

View

<select popover="Choose your input drug, type to filter list of drugs"  data-ng-model="currentData"
   data-ng-options="name.drug_name for name in ourDataName" style="width:300px;" convert-to-number >
</select>
Sign up to request clarification or add additional context in comments.

1 Comment

Change name.name to name.drug_name.
1

Anik's answer is great. But if you want to go with a loop option, you can use the below code in your controller.

$scope.ourDataName = [];
$http.get(URL).success(function (data) {    
  angular.forEach(data, function(drug) {
    $scope.ourDataName.push(drug.drug_name);
  });
});

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.