0

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.

3
  • 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. Commented May 6, 2014 at 4:57
  • This is the only code I have. I need to define options inside the directive. Commented May 6, 2014 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. Commented May 6, 2014 at 5:06

1 Answer 1

2

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

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

Comments

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.