I have a custom directive which I am decorating a <select ng-options="">
with as such...
<select custom ng-model="selected" ng-options="o for o in values">
with custom
as my directive and values
being a simple array. Here is my implementation...
<select custom ng-model="selected" ng-options="o for o in values">
<option value selected>uhh?</option>
</select>
app.directive('custom', [function() {
return {
scope: {},
link: function(scope, elem, attrs) {
// how can I get my array of values here?
}
}
}])
app.controller('ctrl', ['$scope', function($scope) {
$scope.values = ['er', 'um', 'eh'];
}])
Within my link
I can see it as such
console.log(attrs.ngOptions);
Which, in this case, logs out the literal "o for o in values"
. Can I somehow parse or compile this within my link
to get the array? I see I can grab it if I do something like scope.$parent.values
, but this seems unnecessary and I would need to know the name of "values"
. I can probably get it through some hacky feeling string manipulation to target it, but I am hoping there is a more intuitive way.
hacky e.g.
var array = attrs.ngOptions.split(' ').pop(); // "values"
console.log(scope.$parent[array]);
Side note - constricted to AngularJS 1.2.x for this example
JSFiddle Link - example
Look the fiddle below. JsFiddle
As of Angular v1.4, neither
select
norngOptions
directives provide an API to get the array of items that results in<option>
s, so we are only left with 2 choices - 1) pass thevalues
array explicitly tocustom
directive as an attribute value, or 2) derive it from the micro-syntax ofng-options
.With #1 - the approach is straightforward.
With #2 - we would need to parse the microsyntax, for example with
RegExp
. This is fragile, since the micro-syntax may change in the future.We could use Angular's own regex expression (see src v1.4.3) to parse this syntax:
(the 8th group matches the items)
Or, we could make it a simpler regex, perhaps even stabler, for example:
At any rate, the directive would look like so: