AngularJS:带有自定义 ng-options 的下拉指令

标签 angularjs angularjs-directive

我正在尝试创建一个下拉指令,我想通过使用指令属性来指定 selects 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>

fiddle :http://jsfiddle.net/wXV6Z/1/

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

谢谢 /安德烈亚斯

最佳答案

事实上,这是可行的。您需要做的唯一更改是删除 a[{{optValue}}]a[{{optDescription}}] 周围的大括号,就像您不需要的那样不需要在那里插值。

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

Here's an updated version of your fiddle .

关于AngularJS:带有自定义 ng-options 的下拉指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14967416/

相关文章:

javascript - angularjs 无法更新下拉列表更改时的指令

javascript - 使用不显示绝对 url 的 Angular ng-src

javascript - 自定义指令上的 Angular 属性困惑

javascript - Angular ng-repeat 的调用输入焦点更改

javascript - AngularJS - 在 HTML 中调用函数

angularjs - 无法实例化 Controller Angular 新路由器

javascript - Angular JS 级联通知

单击链接后 Angularjs 更改 View 模板

angularjs - 在 Angular 1.5 组件中注入(inject)服务的示例

css - 如何使 .svg 图标对禁用状态使用react并更改其颜色?