[英]How can I access a selected option's displayed value from a directive on the select element
My markup looks something like this 我的标记看起来像这样
<select ng-model="search.parameters.selectedOptionId" ng-options="lookup.id as lookup.lookupValue for lookup in lookups.options" custom-attribute-directive>
<option value="" selected>All</option>
</select>
From the customAttributeDirective, I need to access the selected option value that is displayed in the dropdown (ie lookup.lookupValue). 从customAttributeDirective中,我需要访问下拉菜单中显示的所选选项值(即lookup.lookupValue)。 I've tried accessing the $viewValue on the ngModel, but it is set to the lookup.id (which I assume is the fault of the way ng-options is set up).
我尝试访问ngModel上的$ viewValue,但是将其设置为lookup.id(我认为这是设置ng-options的方式的错误)。 I cannot modify the implementation of the markup due to the circumstances that I am implementing the directive against, so the problem must be solved there.
由于我要针对其实施指令的情况,我无法修改标记的实现,因此必须在那里解决问题。
Bind the lookup.lookupValue for display and lookup.lookupValue for backend Id too. 也将lookup.lookupValue绑定到显示,并将lookup.lookupValue绑定到后端ID。 In that case you will get display text with ng-model
在这种情况下,您将获得带有ng-model的显示文本
<select ng-model="search.parameters.selectedOptionId" ng-options="lookup.lookupValue as lookup.lookupValue for lookup in lookups.options" custom-attribute-directive>
<option value="" selected>All</option>
Found my answer. 找到了我的答案。 It turns out directives can access the dom directly.
事实证明,指令可以直接访问dom。
link: function (scope, element, attrs, controller) {
scope.getViewValue = function () {
if (angular.isDefined(scope.overrideTagDisplay)) {
return scope.overrideTagDisplay;
}
else if (element[0].nodeName == "SELECT") {
return element.children()[element[0].selectedIndex].text;
}
else {
return ngModel.$viewValue;
}
}
scope.initialize()
}
EDIT: I found later that this method has the issue that if javascript modifies the model value somewhere else in the code and then this piece immediately runs, it does not pick up the new value because the DOM hasn't updated (this includes on page load and initial setting). 编辑:稍后我发现此方法存在以下问题:如果javascript在代码中的其他位置修改了模型值,然后此段立即运行,则由于DOM尚未更新,所以它不会获取新值(此内容包括在页面上)负载和初始设置)。 I ended up passing the list of lookups into the directive as well and got around the lack of standardization in those lookups by having an optional "comparator key" that would defaultly look something like
我最终也将查找列表传递到指令中,并通过使用可选的“比较键”(默认情况下类似于)来解决了这些查找中缺乏标准化的问题
var comparitorKey = { id: "id", lookupValue: "lookupValue"};
which is then utilized like this 然后像这样利用
var id = ngModel.$modelValue;
var filtered = scope.lookupList.filter(function (lookup) { return lookup[scope.comparitorKey.id] == id });
return filtered.length > 0 ? filtered[0][scope.comparitorKey.lookupValue] : null;
the idea being that someone could pass in an alternative like 这个想法是有人可以通过类似
var comparitorKey = {id: "userId", lookupValue: "userName" };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.