【问题标题】:AngularJS: Dropdown directive with custom ng-optionsAngularJS:带有自定义 ng-options 的下拉指令
【发布时间】:2013-02-20 06:12:23
【问题描述】:

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

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

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;
    }
};

});

...这就是我想使用它的方式

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

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

谢谢 /安德烈亚斯

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    实际上,这可以工作。您需要做的唯一更改是删除 a[{{optValue}}]a[{{optDescription}}] 周围的花括号,因为您不需要在那里进行插值。

    optValueoptDescription 已经是范围内的字符串,因此 a[optValue]a[optDescription] 将使您的代码正常工作,因为它们是在指令范围内评估的表达式。

    Here's an updated version of your fiddle.

    【讨论】:

    • 好电话。由于每个部分都由 Angular 评估,因此它将能够将这些值从 $scope 中提取出来。
    • 这正是我正在寻找的。非常感谢!
    • 这帮助我解决了我在自己的自定义指令中遇到的问题,该指令与此非常相似。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多