4

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good call. Since each part is being evaluated by Angular, it will be able to pull those values out of the $scope.
This helped me resolve an issue I was having in my own custom directive doing something very similar to this. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.