无法为 ng 选择分配旧值?



html

<select ng-model="selectedName" ng-change="retrieveSelectedClass(selectedName, '{{selectedName}}')" ng-options="item.name group by item.groupName for item in names"
class="code-helper" id="code-helperId">
<option value="">Select Option</option>
</select>

JavaScript

$scope.retrieveSelectedClass = function(newValue, oldValue) {
if (!globalEditor1.isClean()) {
var r = confirm("You have unsaved changes, are you sure you want to proceed ?");
if (r != true) {
oldValue = JSON.parse(oldValue);
var oldValueObject = {
name: oldValue.name,
id: oldValue.id,
groupName: oldValue.groupName,
lineNumberError : oldValue.lineNumberError,
isCompilationError : oldValue.isCompilationError,
dataNotMatching : oldValue.dataNotMatching,
timeStampNotMatching : oldValue.timeStampNotMatching
};
$scope.selectedName = oldValueObject;
$scope.isPaneShown = false;
return;
}
}
}

所以js做什么,它会检查编辑器是否清晰,然后提醒用户。如果用户选择取消,则 ng-select 中的选定值应保留为旧值,而不是用户选择的新值。

但是,当用户单击"cancel"时,ng-select 中的选定值变为空白? 知道我在哪里犯了错误吗?或者如何实现这一点?

因为在angularjs中,一个对象有一个objectHash(名为$$objectHash如果你调试,你会看到它(。它是一个标识符,您无法分配以选择不在选择选项中的对象。

我用一个例子写了一个 Plunker。我认为这对您有所帮助 https://plnkr.co/edit/YpwhgKSy24kFyYtjRKsv

$scope.retrieveSelectedClass = function(newValue, oldValue){
// your control, i do simple control because i don't understand exatly what you need
if(angular.isUndefined(oldValueSelected.id) && oldValue.indexOf('"id"') !== -1){
oldValueSelected = JSON.parse(oldValue);
}
}
$scope.clearSelect = function(){
// check if old value isn't empty
if(angular.isDefined(oldValueSelected.id)){
// filter names array and get object of old value
var possibleOldValues = $filter('filter')($scope.names, {id: oldValueSelected.id}, true);
if(possibleOldValues.length > 0){
$scope.selectedName = possibleOldValues[0];
}
}
else{
$scope.selectedName = {};
}
}

最新更新