Reputation:
I have two little issues when I populate my select with angularjs.
I wnat populate my select with results from an api rest (I used mocky)
My index.html:
<!DOCTYPE html>
<html ng-app="test">
<head>
<meta charset="utf-8">
<script src="angular.min.js"></script>
<script src="app.js"></script>
<title>My first app</title>
</head>
<body>
<h1>My first app</h1>
<div ng-controller="DemoCtrl">
<select ng-model="selectedTestAccount"
ng-options="item.id as item.name for item in testAccounts">
<option value="">Select Account</option>
</select>
{{error}}
</div>
</body>
</html>
My app.js:
(function () {
'use strict';
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: 'http://www.mocky.io/v2/5a2112be2d0000040ee000aa'
}).then(function (result) {
$scope.testAccounts = result;
}).catch(function (err) { $scope.error = err});;
});
})()
API: http://www.mocky.io/v2/5a2112be2d0000040ee000aa
which returns:
{"id" : 1, "name" : "France - Mainland", "desc": "some description"}
Now I have 2 problems:
as you can see I have the first field correct, but in the other undefined and I don't know why
The second problem is if I have a list of object from API, for example changing url of the call with http://www.mocky.io/v2/5a2132f32d00006116e00178, which returns:
[{"id" : 1, "name" : "France - Mainland", "desc": "some description"}, {"id" : 2, "name" : "Italy", "desc": "some description"}]
I have all option field like undefined (see picture below)
What's wrong?
Thanks!
Upvotes: 0
Views: 291
Reputation: 57
<select ng-model="selectedTestAccount" ng-if="item.name"
ng-options="item.id as item.name for item in testAccounts">
<option value="">Select Account</option>
</select>
ng-if will allow when only the value is defined
Upvotes: 0
Reputation: 222722
The issue is your api returns only one data, which is an object. you need to push the response to your testAccounts array as follows,
$http({
method: 'GET',
url: 'https://www.mocky.io/v2/5a2112be2d0000040ee000aa'
}).then(function(result) {
$scope.testAccounts.push(result.data);
console.log($scope.testAccounts);
}).catch(function(err) {
$scope.error = err
});
Upvotes: 1