2

I'm making a directive that mimics a <select>, but allows me more styling, but couldn't find any information on how to implement it using ng-model. Here's the directive:

.directive('customSelect', [function() {
        return {
            restrict:'EA',
            require: "ngModel",
            scope:{
                choices:"=",
                selected:"="
            },
            template:'\
                <div class="custom-select">\
                    <div class="label">{{ selected }}</div>\
                    <ul>\
                        <li data-ng-repeat="choice in choices" data-ng-click="ngModel = choice">{{ choice }}</li>\
                    </ul>\
                </div>',
            replace:true
        }
}])

How can I set ng-model from the click event on the <li> ?

1 Answer 1

5

Try ngModel.$setViewValue:

app.directive('customSelect', [function() {
        return {
            restrict:'EA',
            require: "?ngModel",
            scope:{
                choices:"=",
                selected:"@"
            },
            link:function(scope,element, attrs,ngModel){
              scope.select = function (choice){
                 ngModel.$setViewValue(choice);
              }
            },
            templateUrl:"template.html",
            replace:true
        }
}])

Template:

<div class="custom-select">
  <div class="label">{{ selected }}</div>
  <ul>
    <li data-ng-repeat="choice in choices" data-ng-click="select(choice)">{{ choice }}</li>
  </ul>
</div>

DEMO (click on an item to see output)

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

2 Comments

the demo is not complete.
@StarsSky: ah, problem when saving, I'll create the demo again

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.