如何创建一个为 ng-options 提供值的指令? [英] How to create a directive that provides values for ng-options?

查看:21
本文介绍了如何创建一个为 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).

有没有办法创建一个指令来为 ng-options 提供值/表达式?

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

例如,其中 my-options-months 将自动创建值为 1..12 的选项code> 使用 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.

推荐答案

更新答案您的指令是这样的:

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/

这篇关于如何创建一个为 ng-options 提供值的指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆