简体   繁体   中英

iterating over a json array to fill a dropdown - angularjs

I have a json array from a json response of this nature

data {"success":true,"errorCode":0,"data":["kkkk-kkkk 1","oooo-ooooo 2"]}
  1. Item 1 is expected to be >>> kkkk-kkkk 1
  2. Item 2 is expected to be >>> oooo-ooooo 2

in angular script controller I am doing this to push the array into the html view

else if (res.status == 200) { 
    $scope.partners = []; 
    var myJSON = res.data; 
    console.log("data" + JSON.stringify(res.data));
    angular.forEach(myJSON, function (item) { 

    $scope.activities.push(item);

I want to get the json arrays to fill a dropdown of this is a challenge

<select ng-model="act" formcontrol class="ui fluid dropdown ng-untouched ng-pristine ng-valid" required>
  <option ng-repeat="a in activities" value="{{a}}">{{a}}</option>
</select>

Please assist

Actually you are iterating the wrong array, you are iterating the object instead.

Because in your code:

console.log("data" + JSON.stringify(res.data));

Will give you:

data {"success":true,"errorCode":0,"data":["kkkk-kkkk 1","oooo-ooooo 2"]}

So you need to store res.data.data in your myJSON variable, or the best would be to assign this array directly in your $scope.activities :

$scope.activities = res.data.data;

And in your HTML:

<select ng-model="act" formcontrol class="ui fluid dropdown ng-untouched ng-pristine ng-valid"  ng-options="option for option in activities"required>
</select>

使用ng-options

ng-options="item as item for item in activities" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM