我已经实现了一个选择下拉菜单,用于过滤项目列表。我正在寻找一个隐藏选择下拉列表的指令,并使用相同的选项将其替换为自定义下拉列表并保持相同的功能。
选择
<select ng-model="selectedLocation" ng-options="location.title group by location.group for location in locations | orderBy:['-group', 'title'] track by location.title">
<option value="">Location</option>
</select>
locations Array:
[
{
title: 'New York',
group: 'USA'
},
{
title: 'California',
group: 'USA'
},
{
title: 'London',
group: 'Outside USA'
}
]
期望的输出:
<div class="active">Location</div>
<div class="options">
<span class="optgroup">USA</span>
<span class="option">New Jersey</span>
<span class="option">New York</span>
<span class="optgroup">Outside USA</span>
<span class="option">London</span>
</div>
// hidden, but value still binding to controller
<select ng-model="selectedLocation" style="display:none">...</select>
任何帮助解决这个问题都会非常感激!
谢谢!
答案 0 :(得分:0)
我建议您查看Angular的Select2插件...
答案 1 :(得分:0)
为了将完全相同的功能放入指令中,这是一个基本的代码片段,可以做到这一点。
备注:这与J.C.的使用angular-ui的select2指令的提议不同,后者是一个更好,更强大,但也更复杂的解决方案......
angular.directive('locationSelector', [function () {
return {
restrict: 'E',
template: '<ng-form><select ng-model="selectedLocation" ng-options="location.title group by location.group for location in locations | orderBy:[\'-group\', \'title\'] track by location.title"><option value="">Location</option></ng-form>',
require: 'ngModel',
scope: {
'locations': '='
},
replace: true,
link: function (scope, iElement, iAttrs, ngModel) {
ngModel.$render = function () {
scope.location = ngModel.$modelValue;
};
scope.$watch('selectedLocation', function (newVal) {
ngModel.$setViewValue(newVal);
});
}
};
}]);
像这样使用:
<location-selector ng-model="location" locations="locations"></location-selector>