Reputation: 3328
I'm new in angularjs and I have a problem with values from http request. I use this values to populate an Select field but I can't set the default value (for example the first element of array). This is my javascript code:
var app = angular.module('myApp',[]);
app.controller('freeUserController', function($scope, $http) {
$http({
method: 'GET',
url: 'users'
}).then(function successCallback(response) {
$scope.users = response.data.result;
$scope.selectedItem = $scope.users[0];
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
});
Instead on my html code I have
<label>Username</label> <select class="form-control select2"
style="width: 100%;" name="user" ng-model="selectedItem" ng-options="user.username for user in users">
</select>
If I change the result of http request with static array all works fine. Are you know why I have this problem?
Before I used this thymeleaf code with success:
<div class="form-group" id=existingUser>
<label>Username</label> <select class="form-control select2"
style="width: 100%;" th:field="*{user}">
<option th:each="user: ${users}" th:value="${user.username}"
th:text="${user.username}"></option>
</select>
</div>
this is the debug image
I tought was a problem of plugin, but with static array it works like with thymeleaf
Upvotes: 1
Views: 491
Reputation: 255
Try this
<select ng-model="selectedItem" ng-options="user.username as user.username for user in users">
<option value="" selected="selected">{{users[0].m}}</option>
</select>
Controller
$scope.selectedItem = $scope.users[0].username;
Upvotes: 0
Reputation: 92
Your using user.username
to display and in script your assigning complete user Object like this
$scope.selectedItem = $scope.users[0];
change this to
$scope.selectedItem = $scope.users[0].username;
This should work now
Upvotes: 1
Reputation: 544
In ng-model give like this and try.
ng-model="selectedItem.username"
Otherwise in controller change like below:
$scope.selectedItem=$scope.users[0].username;
Upvotes: 0
Reputation: 12892
Try to set user.id as user.username
in ng-options
directive.
<select class="form-control select2"
style="width: 100%;" name="user" ng-model="selectedItem" ng-options="user.id as user.username for user in users">
</select>
Upvotes: 0
Reputation: 88
should can easily give the select an "ng-init" like so:
<select class="form-control select2" ng-init="selectedItem = users[0]"
style="width: 100%;" name="user" ng-model="selectedItem" ng-options="user.username for user in users">
Sorry for formating
Upvotes: 0