简体   繁体   中英

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). 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). 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. In that case you will get display text with 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.

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). 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" };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM