gpt4 book ai didi

javascript - Angular 动态选择值

转载 作者:行者123 更新时间:2023-11-30 17:19:13 24 4
gpt4 key购买 nike

我在选择中有一些动态生成的:

<select ng-model="selectedValue" ng-options="o.id as o.name for o in values"></select>

我有 selectedValue 保存选定的值。当 selectedValue 不再出现在 values 中时,我希望将其更新为 nullundefined

我可以清除 $scope.$watch(values) 中的 selectedValue 但有更好的解决方案吗?

基本上是this plunker中的这种情况是我想避免的:

This is what I want to avoid

我希望它是“Selected value: null”或类似的东西。

最佳答案

您可以创建一个指令,使 select 以您喜欢的方式运行。然后 HTML 将更改为:

<select clearable ng-model="selectedValue" ng-options="o.id as o.name for o in values"></select>

指令的 JS 将是:

app.directive('clearable', ['$parse',function($parse){
return {
restrict : 'A',
scope : {
'ngModel' : '=',
'ngOptions' : '@'
},
require: ['select','?ngModel'],
link : function(scope, elem, attr,ctrl){

// Regex copied from the Angular Source
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
var match = scope.ngOptions.match(NG_OPTIONS_REGEXP);

var valuesFn = $parse(match[7]), //Options list
key = match[1].split('.')[1]; //Property in options list

scope.$watch(
function(){
// Watch for when the options list changes
return valuesFn(scope.$parent);
},
function(newList){
var isFound, i,
currentModelVal = scope.ngModel;

// Iterate through the new list to see if the current value is present
for(i=0;i<newList.length;i++){
if (newList[i][key] === currentModelVal){
isFound = true;
break;
}
}

// If not found, reset the ng-model value to null
if (!isFound){
ctrl[1].$setViewValue(null);
}
}
);

}
}
}]);

http://plnkr.co/edit/yAk9YSoMf88rtTqLXTiI?p=preview 查看 Plunker

关于javascript - Angular 动态选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25483853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com