我有一个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
指令来防止这些问题的正确方法是什么?
答案 0 :(得分:2)
您可以为地址查找创建指令,并将查找逻辑移动到指令控制器中。每个指令实例都有自己的控制器实例,因此它有自己的$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=[{}, {}];
});
答案 1 :(得分:0)
您也可以执行以下操作。数组中的每个对象都有其自己的selected
项目。要添加新重复,您只需$scope.repeats.push({})
,而要删除重复,请$scope.repeats.splice(index, 1);
。如果要将$scope.repeats
推送到API,请记住使用angular.toJson($scope.repeats)
而不是JSON.stringify($scope.repeats)
。
原因selected
子项。我有更多物品,所以这对我很有用
file.js
$scope.repeats=[{}, {}];
file.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"
}
}
];