2016-11-04 94 views
0

在此示例中,默認情況下未選擇預定義項目。請幫助實現這一點。使用angularjs預填充選擇框

<button ng-click="addRow()">Add Row</button> 
    <ul> 
    <li ng-repeat="row in rows"> 
     <select kendo-drop-down-list ng-model="row.selected" ng-init="row.selected = row.choosenItem" ng-options="item.name for item in list | filter:notUsed(row)"></select> 
     <button ng-click="deleteRow(row)">X</button> 
    </li> 
    </ul> 

var app = angular.module('plunker', []); 

在row.choosenItem屬性中選擇的數據($ scope.rows)項中。仍然選擇框不填充choosenItem。

app.controller('MainCtrl', function($scope) { 
    $scope.list = [{ 
    id: 1, 
    name: "one" 
    }, { 
    id: 2, 
    name: "Two" 
    }, { 
    id: 3, 
    name: "Three" 
    }, { 
    id: 4, 
    name: "Four" 
    }, { 
    id: 5, 
    name: "Five" 
    }, { 
    id: 6, 
    name: "Six" 
    }]; 
    $scope.rows = [{ 
    choosenItem: { 
     id: 2, 
     name: "Two" 
    }, 
    label: "row 1", 
    selected: 2 
    }, { 
    choosenItem: { 
     id: 4, 
     name: "Four" 
    }, 
    label: "row 2", 
    selected: 4 
    }]; 

    function byID(member) { 
    return member.choosenItem.id; 
    } 

    $scope.notUsed = function(row) { 
    return function(item) { 
     return item.id === row.choosenItem.id || !_.indexBy($scope.rows, byID)[item.id]; 
    } 
    }; 

    $scope.addRow = function addRow() { 
    $scope.rows.push({ 
     choosenItem: {}, 
     label: "row "+($scope.rows.length+1), 
     selected: 0 
    }) 
    }; 

    $scope.deleteRow = function deleteRow(row) { 

    }; 

    $scope.onSelectChange = function onSelectChange(row){ 
    row.choosenItem = _.findWhere($scope.list, {'id': parseInt(row.selected)}); 
    }; 
}); 

Example code here

回答

0

基本上,使用ngOptions當語法value as text for item in array - 所以牢記這一點,定義值:

ng-init="row.selected = row.choosenItem.id" ng-options="item.id as item.name for item in list"