NG 옵션 값을 제공하는 지시문을 만드는 방법은 무엇입니까?
-
26-12-2019 - |
문제
전체 앱에서 동일한 옵션을 갖는 요소를 선택하지만 조금 다르게 볼 수 있습니다.사용자의 생일 (일, 월, 년)을 선택합니다.
ng-options
에 값 / 표현식을 제공하는 지시문을 만들 수있는 방법이 있습니까?
e.g.<select my-options-months></select>
는 my-options-months
지시문을 사용하여 generacodicicetagcode 값을 사용하여 자동으로 옵션을 자동으로 만들 수 있습니다.
해결책
업데이트 된 답변 귀하의 지시문은 다음과 같습니다 :
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);
};
}
}
})
.
제발, 체크 아웃 http://jsfiddle.net/kn9xxx/39/kn/a> / P>
다른 팁
선택에서 값 범위를 만들려면 템플리트에 넣으십시오.범위가 동적이어야하는 경우 지침의 속성에 링크하십시오.
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>
.
는 다음과 같은 필터와 다른 접근법이있을 수 있습니다.
.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;
};
})
. 제휴하지 않습니다 StackOverflow