Question

I've got select elements that have the same options across the whole app, but may look a bit differently, e.g. selects for user's birthday (day, month, year).

Is there a way to create a directive that would provide values/expression for ng-options?

E.g. <select my-options-months></select>, where my-options-months would automatically create options with values 1..12 using ng-options directive.

Was it helpful?

Solution

Updated answer Your directive would like this:

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

Please, checkout fiddle with example http://jsfiddle.net/KN9xx/39/

OTHER TIPS

If you are planning to create a range of values in select just put it in a template. And if the range has to be dynamic just link it to a attribute in a directive.

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=preview

may be with a different approach with a filter like:

.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;
        };
    })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top