How to create a directive that provides values for ng-options?

旧城冷巷雨未停 提交于 2019-12-11 11:07:52

问题


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.


回答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/




回答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>

Demo: http://plnkr.co/edit/tL694zGr5tZJq5L4pwEA?p=preview




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


来源:https://stackoverflow.com/questions/24058188/how-to-create-a-directive-that-provides-values-for-ng-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!