Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to create a dropdown box by the means of directive without creating a separate controller. Here is my code:

index.html

<dropdown option="myoptions" />

script.js

serviceModule.directive('dropdown',function() {
    return {
        restrict: 'EA',
        replace:true,
        scope: {
            options:'='
        },
        template: '<select ng-options="opt in myoptions"></select>',
        controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
            $scope.myoptions = ['1','2','3'];
        }],
    }
});

The script neither produces errors nor displays any options in the dropdown. Could you please explain what I'm doing wrong?

Thanks in advance.

share|improve this question
2  
You might need to show more of your code. It is hard to know exactly what is going on. You seem to be trying to pass options into the directive, but then you are also defining them in the directive's controller. –  aet May 6 at 4:57
    
This is the only code I have. I need to define options inside the directive. –  Sray May 6 at 5:00
    
Where do you define the main app module? Does the main module include the serviceModule? Show the entire index.html please. When you set the options attribute to "myoptions" and then bind it to the isolate scope of your directive you don't need to also define the options in the directive's controller. –  aet May 6 at 5:06

1 Answer 1

up vote 2 down vote accepted

ng-options requires a comprehension expression of the form label for value in array. And you need to add ng-model for select to work.

template: '<select ng-model="choice" ng-options="opt for opt in myoptions"></select>',
controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
    $scope.choice;
    $scope.myoptions = ['1','2','3'];
}],

Here is a working plunker: http://plnkr.co/edit/8a6gwpVnMfvXxZzvQBOs?p=preview

share|improve this answer
    
Thank you so much for the explanation. Exactly what I needed. –  Sray May 6 at 6:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.