Reputation: 3712
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>
?
Upvotes: 2
Views: 5057
Reputation: 48972
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)
Upvotes: 5