如何创建一个为 ng

编程入门 行业动态 更新时间:2024-10-28 16:27:20
本文介绍了如何创建一个为 ng-options 提供值的指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我选择的元素在整个应用程序中具有相同的选项,但看起来可能略有不同,例如选择用户的生日(日、月、年).

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/KN9xx/39/

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

更多推荐

[db:关键词]

本文发布于:2023-04-21 20:19:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1008926.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:创建一个   ng

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!