2017-02-26 58 views
0

我正在用ng-repeat添加ui-selects,但我不知道如何从控制器中的每个ui-select中分别获取值。我想在控制器中获取选定的项目值作为参数发送$ http请求。如何从ui-选择在ng-repeat中获得选定的值

<div ng-repeat="repeat in repeats"> 
    <p>Selected: {{pattern.selected.name}}</p> 
    <ui-select ng-model="repeat.id"> 
<ui-select-match placeholder="Enter an pattern...">{{$select.selected.name}}</ui-select-match> 
<ui-select-choices repeat="pattern in data_pattern_newspapers track by $index"> 
    <div ng-bind-html="pattern.name | highlight: $select.search"></div> 
</ui-select-choices> 

我想下面做出头在我的控制器:

alert($scope.repeat.id.selected) 

我如何可以访问到的每个UI,选择在我的控制器的型号?

plnkr

请一些身体帮我。谢谢!

+0

上'repeat.id'正在改变'id'值从它的初始值,无论你在下拉列表中选择值你的'NG-model'。这可能是也可能不是你想要的;它可能不是,因为你的选择是绑定一个对象:http://plnkr.co/edit/sOrXVNiUQaj5HO3TKJyH?p=preview – Claies

+0

为了使其他人更容易建议替代方案,你可能想解释你是什么计划使用的值。 – Claies

+0

@Claies我想要获取控制器中选定的项目值作为参数发送$ http请求。那么我应该在控制器中做些什么来获得这个选择的项目? –

回答

1

在HTML利用ngRepeat的$index属性来创建针对每个ui-select的独特模式,并通过$index进入ngChange功能:

<ui-select ng-model="selections[$index]" ng-change="selectionChanged($index)"> 

在控制器初始化一个数组来保存所选择的值,并且添加上述功能接收$index引用此数组:

$scope.selections = []; 

$scope.selectionChanged = function(idx) { 
    console.log(idx, $scope.selections[idx]); 
}; 

现在$scope.selections是他们的选择的阵列,因为它们使它们。

演示:http://plnkr.co/edit/NSK3UmelATopV0Juw8BV?p=preview

+0

请注意,'ngChange'函数不是必需的 - 您可以随时参考'$ scope.selections',但是我认为您可能会在选择更改时采取某种操作。然而,关键是使用$ index:'ng-model =“选项[$ index]”' –

+0

是的,确切地说。完美地工作。谢谢! @K Scandrett –