سؤال

لقد حصلت على عناصر محددة لها نفس الخيارات عبر التطبيق بأكمله، ولكنها قد تبدو مختلفة قليلاً، على سبيل المثال.يختار لعيد ميلاد المستخدم (اليوم والشهر والسنة).

هل هناك طريقة لإنشاء توجيه من شأنه أن يوفر قيمًا/تعبيرًا لـ ng-options?

على سبيل المثال <select my-options-months></select>, ، أين my-options-months سيقوم تلقائيًا بإنشاء خيارات ذات قيم 1..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);
            };
        }
    }
})

من فضلك، الخروج كمان مع المثال 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>

العرض التوضيحي: http://plnkr.co/edit/tL694zGr5tZJq5L4pwEA?p=preview

قد يكون مع نهج مختلف مع مرشح مثل:

.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