Ashok Reddy Ashok Reddy - 4 months ago 29
Javascript Question

Unable to bind data to dropdown-multiselect in angularjs

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.

demo plunker

Answer
//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);
Comments