问题
I'm trying to create a dropdown directive where i want to specify the selects ng-options "option value" and "option description" attributes by specifying them with the directives attributes. See code for a better understanding...
Here is my directive. This will obviously not work, but i think it will describe what i'm trying to do...
app.directive('dropdown', function(){
return {
restrict: 'E',
scope: {
array: '='
},
template: '<label>{{label}}</label>' +
'<select ng-model="ngModel" ng-options="a[{{optValue}}] as a[{{optDescription}}] for a in array">' +
'<option style="display: none" value="">-- {{title}} --</option>' +
'</select>',
link: function (scope, element, attrs) {
scope.label = attrs.label;
scope.title = attrs.title;
scope.optValue = attrs.optValue;
scope.optDescription = attrs.Description;
}
};
});
...and here is how i want to use it
<dropdown title="Choose ferry" label="Ferries" array="ferries" opt-value="Id" opt-description="Description"></dropdown>
<dropdown title="Choose route" label="Routes" array="routes" opt-value="Code" opt-description="Name"></dropdown>
And the fiddle: http://jsfiddle.net/wXV6Z/1/
If you have a solution to this problem, or perhaps more likely, have a different opinion on how to tackle it, please let me know!
Thanks /Andreas
回答1:
Actually, this can work. The only change you need to make is to remove the curly braces around a[{{optValue}}]
and a[{{optDescription}}]
, as you don't need to interpolate there.
optValue
and optDescription
are already strings in scope, so a[optValue]
and a[optDescription]
will make your code work just fine, as they are expressions evaluated in your directive's scope.
Here's an updated version of your fiddle.
来源:https://stackoverflow.com/questions/14967416/angularjs-dropdown-directive-with-custom-ng-options