我有一个ui-select
它被包装在ng-repeat
指令中。由于它们共享相同的范围,因此我有几个问题:
-
在第一个选择中选择值后,第二个选择已经预先填充了我首先输入的内容。
-
占位符是隐藏的,仅当"选择字段"处于焦点时显示。
这是 html:
<div ng-repeat="repeat in repeats">
<p>Selected: {{repeat.id.formatted_address}}</p>
<ui-select ng-model="repeat.id"
theme="bootstrap"
ng-disabled="disabled"
reset-search-input="false"
style="width: 300px;">
<ui-select-match placeholder="Enter an address...">{{$select.selected.formatted_address}}</ui-select-match>
<ui-select-choices repeat="address in addresses track by $index"
refresh="refreshAddresses($select.search)"
refresh-delay="0">
<div ng-bind-html="address.formatted_address | highlight: $select.search"></div>
</ui-select-choices>
</ui-select>
</div>
问题是使用多个ui-select
指令来防止这些问题的正确方法是什么?
演示普伦克
您可以为地址查找创建指令,并将查找逻辑移动到指令控制器中。每个指令实例都有自己的控制器实例,因此也有自己的$scope.addresses
实例(防止预填充第二个选择和第一个选择的行为)。
<div ng-repeat="repeat in repeats">
<address-selector repeat="repeat"></address-selector>
</div>
app.directive('addressSelector', function() {
return {
restrict: 'E',
scope: {
repeat: '='
},
template:
'<p>Selected: {{repeat.id.formatted_address}}</p>' +
'<ui-select ng-model="repeat.id"' +
' theme="bootstrap"' +
' ng-disabled="disabled"' +
' reset-search-input="false"' +
' style="width: 300px;">' +
'<ui-select-match placeholder="Enter an address...">{{$select.selected.formatted_address}}</ui-select-match>' +
'<ui-select-choices repeat="address in addresses track by $index"' +
' refresh="refreshAddresses($select.search)"' +
' refresh-delay="0">' +
' <div ng-bind-html="address.formatted_address | highlight: $select.search"></div>' +
'</ui-select-choices>' +
'</ui-select>',
controller: function ($scope, $http) {
$scope.refreshAddresses = function(address) {
var params = {address: address, sensor: false};
return $http.get(
'http://maps.googleapis.com/maps/api/geocode/json',
{params: params}
).then(function(response) {
$scope.addresses = response.data.results
});
};
}
};
});
要显示 ui-select 占位符,应避免初始化模型 ( repeat.id
),或将其设置为 null
。
app.controller('DemoCtrl', function($scope) {
$scope.repeats=[{}, {}];
});
更新的普伦克
你也可以做这样的事情。数组中的每个对象都有自己的selected
项。要添加新的重复,您只需$scope.repeats.push({})
,删除重复$scope.repeats.splice(index, 1);
。如果要将$scope.repeats
推送到 API,请记住使用 angular.toJson($scope.repeats)
而不是 JSON.stringify($scope.repeats)
。
原因selected
如果您只有该数据,则不需要该子项。我有更多的物品,所以这对我很有用
文件.js
$scope.repeats=[{}, {}];
文件.html
<div ng-repeat="repeat in repeats">
<p>Selected: {{repeat.selected.formatted_address}}</p>
<ui-select ng-model="repeat.selected">
<ui-select-match placeholder="Enter an address...">
{{$select.selected.formatted_address}}
</ui-select-match>
<ui-select-choices repeat="address in addresses track by $index">
<div ng-bind-html="address.formatted_address | highlight: $select.search"></div>
</ui-select-choices>
</ui-select>
</div>
输出数据可能如下所示:
$scope.repeats == [
{
selected: {
formatted_address: "98 Hubin Middle Rd"
}
},
{
selected: {
formatted_address: "100 Rogwart Way"
}
}
];