AngularJS:下拉指令定制NG选项 [英] AngularJS: Dropdown directive with custom ng-options
问题描述
我试图创建一个下拉指令,我想指定选择NG-选项选项值和选项的说明通过与指令属性指定它们的属性。见code为了更好地理解...
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/
And the fiddle: 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!
谢谢
/安德烈亚斯
Thanks /Andreas
推荐答案
其实,这是可行的。你需要做的唯一的变化是去掉周围的花括号 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.
optValue
和 optDescription
已经在范围字符串,所以 A [optValue]
和 A [optDescription]
会让你的code的工作就好了,因为他们是在你的指令的范围进行评估前pressions。
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选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!