2012-10-26 20 views
0

我正在構建一個CRUD,並且我想要將某個模型鏈接到其他模型。因此,在某些更新/創建模板中,我需要添加其他模型並在提交表單時保存它們的ID。 所以我做了一個由我的後端服務的基本表單。這裏是我嘗試顯示鏈接模型中的一部分:AngularJS:需要將選定的集合附加到模型

<div ng-repeat="item in otherItems"> 
    <select ng-model="item" name="item" > 
     <option value="1" ng-selected="item"> 
     <option value="2" ng-selected="item"> 
     <option value="3" ng-selected="item"> 
    </select> 
    <a class="remove" ng-click="removeRelated(item)">remove</a> 
</div> 
<a ng-click="addRelated()"><i class="icon-plus"></i></a> 

注:otherItems可能是在一開始空(做當創建或當一個項目不會鏈接到任何其他相關模型的項目)。 所以,當一個按添加/刪除它會觸發控制器的功能:

$scope.addRelated = function(){ 
    if (typeof $scope[otherItems]=="undefined") 
     $scope[otherItems] = new Array(); 

    $scope[otherItems].push($scope[otherItems].length); 
}; 

$scope.removeRelated = function (item){ 
    console.debug(item); 
    var idx = $scope[otherItems].indexOf(item); 
    if (idx !== -1) { 
     $scope[otherItems].splice(idx, 1); 
    } 
}; 

我的問題是,當我救我得到項目中的項目位置(所以它總是0,1,2 ...)我將不會有一個選定ID的數組。 我想我的addRelated可能有問題。我究竟做錯了什麼?

下面是截圖,瞭解的想法,因爲我可能不是很清楚: enter image description here

+0

你有一個小提琴或一個[plunk](http://plnkr.co)正是你想要做的?上面的代碼看起來像psuedocode。 –

+0

我會盡量在稍後再做一個JsFiddle。但你猜我想。 – Spir

回答

1

所以這樣的事情? http://plnkr.co/edit/6eqWL5

的標記..

<body ng-controller="MainCtrl"> 
    <div ng-repeat="otherItem in otherItems"> 
    <select ng-model="otherItem.selectedItem" ng-options="item for item in otherItem.items"></select> 
    <a ng-click="removeOtherItem($index)">remove</a> 
    </div> 
    <a ng-click="addOtherItem()">add</a> 
    <hr/> 
    Selected: 
    <ul> 
    <li ng-repeat="otherItem in otherItems"> 
     otherItem[{{$index}}].selectedItem = {{otherItem.selectedItem}} 
    </li> 
    </ul> 
</body> 

代碼

app.controller('MainCtrl', function($scope) { 
    $scope.otherItems = [ 
     { 
     selectedItem: null, 
     items: [1, 2, 3] 
     }, 
     { 
     selectedItem: null, 
     items: [4, 5, 6] 
     } 
    ]; 
    $scope.addOtherItem = function(){ 
    $scope.otherItems.push({ items: [7, 8, 9]}); 
    }; 
    $scope.removeOtherItem = function(index) { 
    $scope.otherItems.splice(index, 1); 
    }; 
}); 

很抱歉,如果它從你問...什麼的問題有點模糊的了,所以我猜測一些功能。

+0

非常抱歉模糊。我的英語不好。下拉列表已經從我的後端代碼生成。所以每個添加的下拉列表都是相同的(「同一模型」列表)。示例:您可以編輯用戶,該用戶鏈接到0到任何組。因此,當您編輯用戶時,您可以將其鏈接到組。我想我會通過讓用戶添加一個新的下拉菜單並選擇要匹配的組來實現這一點。然後,在提交表單時,每個組標識都將發送到名爲group的數組中。在我真正的例子中,我試圖讓它幹,所以我將使用任何模型的代碼是CRUD(這可能解釋爲什麼我模糊) – Spir

+0

也許我應該使用模板: '

相關問題