无法将数据绑定到angularjs中的dropdown-multiselect

时间:2016-07-08 05:53:14

标签: javascript angularjs

请检查弹药。我无法绑定来自服务器的数据,如(["Monday","Tuesday"])

我知道数据会像

那样绑定
$scope.selectedUser = [{ id: 2, name: 'Monday' },
                       {id: 3,name:'Tuesday'}];.

我想在javascript中将["Monday","Tuesday"]设为[{ id: 2, name: 'Monday' },{id: 3,name:'Tuesday'}],以便它会在下拉列表中绑定。

请帮我解决这个问题。

demo plunker

4 个答案:

答案 0 :(得分:1)

你可以这样做

$scope.selectedUsers=[];
//serverData is data from server
for(var i =0 ; i < serverData.length ; i++){
    $scope.selectedUsers.push({id:i , name: serverData[i]})
}

并以你的角度

$scope.doSelectedUser = function () {
    $scope.selectedUser = $scope.selectedUsers;
}

答案 1 :(得分:1)

$scope.selectedUser应该引用$scope.users中的实际对象。例如,这是我必须在你的plunker中更改绑定它与用户匹配用户名列表的用户:

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;
});

在线演示 - http://plnkr.co/edit/3TOkZEaZVSxtpNbFaNkg?p=preview

您提到要从服务器的响应中执行此操作。根据您的示例,假设您依靠名称默认选择的用户,目前还不清楚您希望如何决定选择哪一个。

这是您处理服务器响应的方式并修改新选定的用户:

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;
        });
    });

您可以将过滤条件更改为对您有意义的

答案 2 :(得分:1)

使用以下代码

实现您的json
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+"]")

答案 3 :(得分:1)

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