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

前端之家收集整理的这篇文章主要介绍了AngularJS:具有自定义ng-options的下拉指令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个下拉指令,我想指定选择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/

如果你有解决这个问题的方法,或者更有可能,对如何处理它有不同的意见,请告诉我!

谢谢
/安德烈亚斯

解决方法

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

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

Here’s an updated version of your fiddle.

猜你在找的Angularjs相关文章