AngularJS:带有自定义 ng-options 的下拉指令 [英] AngularJS: Dropdown directive with custom ng-options

查看:22
本文介绍了AngularJS:带有自定义 ng-options 的下拉指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个下拉指令,我想通过使用指令属性指定它们来指定选择 ng-options选项值"和选项描述"属性.查看代码以获得更好的理解...

I'm trying to create a dropdown directive where i want to specify the selects ng-options "option value" and "option description" attributes by specifying them with the directives attributes. See code for a better understanding...

这是我的指令.这显然行不通,但我认为它会描述我正在尝试做的事情......

Here is my directive. This will obviously not work, but i think it will describe what i'm trying to do...

app.directive('dropdown', function(){
return {
    restrict: 'E',
    scope: {
        array: '='
    },
    template:   '<label>{{label}}</label>' +
                '<select ng-model="ngModel" ng-options="a[{{optValue}}] as a[{{optDescription}}] for a in array">' +
                    '<option style="display: none" value="">-- {{title}} --</option>' +
                '</select>',
    link: function (scope, element, attrs) {
        scope.label = attrs.label;  
        scope.title = attrs.title;
        scope.optValue = attrs.optValue;
        scope.optDescription = attrs.Description;
    }
};

});

...这是我想如何使用它

...and here is how i want to use it

<dropdown title="Choose ferry" label="Ferries" array="ferries" opt-value="Id" opt-description="Description"></dropdown>
<dropdown title="Choose route" label="Routes" array="routes"  opt-value="Code" opt-description="Name"></dropdown>

还有小提琴:http://jsfiddle.net/wXV6Z/1/

如果您有解决此问题的方法,或者更有可能对如何解决此问题有不同意见,请告诉我!

If you have a solution to this problem, or perhaps more likely, have a different opinion on how to tackle it, please let me know!

谢谢/安德烈亚斯

推荐答案

实际上,这行得通.您需要做的唯一更改是删除 a[{{optValue}}]a[{{optDescription}}] 周围的大括号,因为您不需要不需要在那里插值.

Actually, this can work. The only change you need to make is to remove the curly braces around a[{{optValue}}] and a[{{optDescription}}], as you don't need to interpolate there.

optValueoptDescription 已经是作用域中的字符串,所以 a[optValue]a[optDescription]将使您的代码正常工作,因为它们是在您的指令范围内计算的表达式.

optValue and optDescription are already strings in scope, so a[optValue] and a[optDescription] will make your code work just fine, as they are expressions evaluated in your directive's scope.

这是您的小提琴的更新版本.

这篇关于AngularJS:带有自定义 ng-options 的下拉指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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