2015-07-13 131 views
0

我知道有很多這方面的問題,但我有最煩人的時間計算如何處理選擇選項值和選擇哪一個。我有一個簡單的項目,我傳遞到模態窗口。此產品包含template_id。我也有templates其中有一個名字和一個ID,我希望創建一個簡單的選擇,其中其中有項目的template_id值的選項被選中:選擇AngularJS選項

<select name="templateId"> 
    <option value="8000">name</option> 
    <option value="8001" selected>name 2</option> 
</select> 

現在用AngularJS我這樣做:

<select name="templateId" 
    ng-model="domain.templateId" 
    ng-options="t.template_id as t.name for t 
       in templates track by t.template_id"> 
     <option value="">Choose template</option> 
</select> 

在我與設定的「選擇」值,所述控制器:

Data.get('templates').then(function(result) { 
    $scope.templates = result; 
}); 

$scope.domain = { 
    template_id: item.template_id, 
    templateId: { template_id: item.template_id } 
}; 

其實我已經得到一個點,我可以發送template_id到REST API和那裏的迴應爲

template_id: 8000 

但是,在select元素中存在一些輕微的煩人行爲。我得到了我想要的項目,但是當我嘗試選擇另一個選項時,它會將選中的項目切換到預設的「選擇模板」選項,但該值或「實際選定的項目」仍然是原始的「選定」值I在控制器中設置。我可以在REST API響應中看到它。但這不是我選擇的。在這個最初的bug後,它會繼續工作,但我該如何擺脫這個問題?

+0

相反templateId的:{template_id:item.template_id}做templateId:item.template_id –

+0

行不通的。它不會設置選定的值。 – Rcls

+0

ng-selected maybe!?! https://docs.angularjs.org/api/ng/directive/ngSelected – sbaaaang

回答

0

這裏有一個例子來解決你的問題。

angular.module('app.select', []) 
 
    .controller('SelecetCtrl', function($scope) { 
 
    $scope.templates = [{ 
 
     template_id: 1, 
 
     name: 'tst1' 
 
    }, { 
 
     template_id: 2, 
 
     name: 'tst2' 
 
    }, { 
 
     template_id: 3, 
 
     name: 'tst3' 
 
    }]; 
 

 
    $scope.selected = { 
 
     template: { 
 
     template_id: 2 
 
     } 
 
    }; 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app='app.select'> 
 
    <div ng-controller='SelecetCtrl'> 
 
    <select name="templateId" ng-model="selected.template" 
 
      ng-options="t as t.name for t 
 
       in templates track by t.template_id"> 
 
     <option value="">Choose template</option> 
 
    </select> 
 
    </div> 
 
</div>

+0

那麼答案就在那裏,只是不太明顯。必須刪除t.id並將其保留爲t。否則,您的示例與我的代碼幾乎完全相同,您只是在$ scope.domain之外創建了選定內容 – Rcls