我在整个应用程序中都有选择相同的选项,但可能看起来有点不同,例如选择用户的生日(日,月,年)。
有没有办法创建一个为ng-options
提供值/表达式的指令?
E.g。 <select my-options-months></select>
,其中my-options-months
会使用1..12
指令自动创建值为ng-options
的选项。
答案 0 :(得分:4)
更新回答 你的指令是这样的:
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
$scope.selectedMonth = 3
})
.directive('myOptionsMonths', function ($compile) {
return {
priority: 1001, // compiles first
terminal: true, // prevent lower priority directives to compile after it
compile: function (element, attrs) {
element.attr("ng-options", "m for m in months");
element.removeAttr('my-options-months'); // necessary to avoid infinite compile loop
var fn = $compile(element);
return function (scope) {
scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
fn(scope);
};
}
}
})
答案 1 :(得分:0)
如果您打算在select中创建一系列值,只需将其放入模板中即可。如果范围必须是动态的,只需将其链接到指令中的属性即可。
app.directive('myOptionsMonths', function(){
return {
scope: {
myOptionsMonths:"@"
},
link: function(scope,e, a){
var N = +a.myOptionsMonths;
scope.values = Array.apply(null, {length: N}).map(Number.call, Number);
},
template: "<select ng-model='t' ng-options='o for o in values'></select>"
};
});
<my-options-months my-options-months="10"></my-options-months>
答案 2 :(得分:0)
可能采用不同的方法,使用过滤器,如:
.filter('range', function () {
return function (input, min, max, padding){
min = parseInt(min);
max = parseInt(max);
padding = padding ? padding : false;
for (var i=min; i<=max; i++){
input.push(padding ? ("00" + i).slice (-2) : i + '');
}
return input;
};
})