Reputation: 174
Please check the plunker. I'm not able to bind the data which come from server like this(["Monday","Tuesday"])
.
I know data binds when it is like
$scope.selectedUser = [{ id: 2, name: 'Monday' },
{id: 3,name:'Tuesday'}];.
I want to make ["Monday","Tuesday"]
to [{ id: 2, name: 'Monday' },{id: 3,name:'Tuesday'}]
in javascript so that it would bind in dropdown.
Please help me solve this issue.
Upvotes: 3
Views: 447
Reputation: 2035
//This is the ng filter to create id as you get the data from server
app.filter('createId',function(){
return function(arr){
var result = [];
for(var i = 0;i < arr.length;i++){
var id = arr[i].substring(0,3);
var obj = {'id':id,'name':arr[i]};
result.push(obj);
}
return result;
}
});
//In js controller you can costomize your array of user by using ng-filter like this
$scope.users = $filter('createId')($scope.users);
//This is because index will be changed every time so this can't be used as ID
$scope.selectedUser = $filter('createId')($scope.selectedUser);
Upvotes: 1
Reputation: 34257
$scope.selectedUser
should have a reference to the actual objects in $scope.users
. for example, this is what i had to change in your plunker to bind it with the users match the user names list:
var defaultSelectedUsers = ["Sunday","Tuesday"];
$scope.users = [
{ id: 1, name: 'Sunday' },
{ id: 2, name: 'Monday' },
{ id: 3, name: 'Tuesday' } ];
$scope.selectedUser = $scope.users.filter(function(user){
return defaultSelectedUsers.indexOf(user.name) != -1;
});
Online Demo - http://plnkr.co/edit/3TOkZEaZVSxtpNbFaNkg?p=preview
You mentioned you want to do it from your server's response. it's unclear how you want to decide which one to select, assuming you rely on a default selected users by name according your example.
This is how you handle a server's response and modify the new selected users:
var defaultSelectedUsers = ["Sunday","Tuesday"];
$http.get('/api/v1/users')
.success(function(users)){
$scope.users = users;
$scope.selectedUser = users.filter(function(user){
return defaultSelectedUsers.indexOf(user.name) != -1;
});
});
You may change the filter condition to what makes sense for you
Upvotes: 1
Reputation: 3128
You can do this
$scope.selectedUsers=[];
//serverData is data from server
for(var i =0 ; i < serverData.length ; i++){
$scope.selectedUsers.push({id:i , name: serverData[i]})
}
And in your angular
$scope.doSelectedUser = function () {
$scope.selectedUser = $scope.selectedUsers;
}
Upvotes: 1
Reputation: 959
Achieve your json using below code
var temp = ["Monday", "Tuesday"]
var result = "[";
for (var i = 0; i < temp.length; i++) {
if(i!=temp.length-1)
{
result += "{id:'" + i + "',name:'" + temp[i] + "'},";
}
else
{
result += "{id:'" + i + "',name:'" + temp[i] + "'}";
}
alert(result);
}
console.log(result+"]")
Upvotes: 1