所以我有一个非常基本的选择,如下所示:
<ui-select theme="select2" search-enabled="false" ng-model="obj.myModel">
<ui-select-match>{{$select.selected.name}}</ui-select-match>
<ui-select-choices repeat="item.value as item in choices">
<span>
{{item.name}}
</span>
</ui-select-choices>
</ui-select>
假设
choices
定义为
$scope.choices = [
{value: 'some_value_1', name: 'Default name'},
{value: 'some_value_2', name: 'Default name 2'}
]
现在假设用户选择了值为
some_value_1
的项目。之后,服务器响应到来,用不同的名称更新 choices
列表
$scope.choices = [
{value: 'some_value_1', name: 'Real name'},
{value: 'some_value_2', name: 'Real name 2'}
]
请注意,模型中保存的值部分保持不变。
<ui-select>
中的名称仍然是默认名称,而我希望将其更改为真实名称。
有没有办法让所选名称对应更新的选择?
[UI-Select 列表更改时不更新当前选定的条目][1]
您在 ui-select 库之外找到了解决方案吗?
我已经在库中提出了一个解决方案来纠正这个问题,因为当选择列表更改时“$select.selected”不会更新, 在代码中,当列表更改时,ui-select 倾向于使用最后一个值,而 item.value 相同。 解决方案1。 下面的代码解释了我所说的。
ngModel.$formatters.unshift(function (inputValue) {
// Keep original value for undefined and null
if (isNil(inputValue)) {
return inputValue;
}
var data = $select.parserResult && $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
locals = {},
result;
if (data){
var checkFnSingle = function(d){
locals[$select.parserResult.itemName] = d;
result = $select.parserResult.modelMapper(scope, locals);
// FIX by aescot https://github.com/angular-ui/ui-select/issues/2038
return angular.equals(result, inputValue);
};
//If possible pass same object stored in $select.selected
// here is the problem when list updated
if ($select.selected && checkFnSingle($select.selected)) {
return $select.selected;
}
for (var i = data.length - 1; i >= 0; i--) {
if (checkFnSingle(data[i])) return data[i];
}
}
return inputValue;
});
修复:添加一行
ctrl.selected = undefined;
$scope.$watchCollection(ctrl.parserResult.source, function(items) {
if (items === undefined || items === null) {
// If the user specifies undefined or null => reset the collection
// Special case: items can be undefined if the user did not initialized the collection on the scope
// i.e $scope.addresses = [] is missing
ctrl.items = [];
} else {
if (!angular.isArray(items)) {
throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items);
} else {
//Remove already selected items (ex: while searching)
//TODO Should add a test
ctrl.refreshItems(items);
//update the view value with fresh data from items, if there is a valid model value
if(angular.isDefined(ctrl.ngModel.$modelValue)) {
ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
// clear $select.selected to force update on $select.selected
ctrl.selected = undefined;
}
}
}
});
解决方案2(理论): 创建您的指令并将其添加到指令中, 在您的指令中,您需要 require 'uiSelect' 来获取控制器 以及链接函数中的访问 $select,
link: function(scope, element, attrs, $select) {
更新列表时设置“$elect.selected = undefined”
您需要将其包装在绑定到服务的函数中才能打开此函数