質問

アプリ全体で同じオプションを持つ要素を選択しましたが、少し異なるように見えます。ユーザーの誕生日(日、月、年)を選択します。

ng-optionsの値/式を提供するディレクティブを作成する方法はありますか?

e.g。<select my-options-months></select>は、my-options-months1..12ディレクティブを使用して値ng-optionsを使用してオプションを自動的に作成します。

役に立ちましたか?

解決

更新された答え あなたの指令が欲しいです:

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);
            };
        }
    }
})
.

example http://jsfiddle.net/kn9xx/39/

他のヒント

選択内の範囲の値を作成する予定の場合は、テンプレートに入れるだけです。範囲が動的でなければならない場合は、指令内の属性にリンクしてください。

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>
.

demo: http://plnkr.co/edit/tl694zgr5tzjq5l4pwea?p=previewed/a.>

は、次のようなフィルターとは異なるアプローチで使用できます。

.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;
        };
    })
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top