我正在制作一个模仿<select>
的指令,但允许我更多样式,但无法找到有关如何使用ng-model实现它的任何信息。这是指令:
.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
}
}])
如何从<li>
上的点击事件设置ng-model?
答案 0 :(得分:5)
尝试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
}
}])
模板:
<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(点击某个项目查看输出)