How To Create A Directive That Provides Values For Ng-options?
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 cre
Solution 1:
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/
Solution 2:
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>
Solution 3:
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;
        };
    })
Post a Comment for "How To Create A Directive That Provides Values For Ng-options?"