Ila*_*ala 4 javascript select angularjs ng-options
我目前在我的指令上有以下指令select.
ng-options="option.value as option.title for option in exportTypes"
$ scope.exportTypes =与每个对象的数组title,value和generatesFile属性.我希望将generatesFile属性添加为为此select生成的data-generates-file每个属性的属性<option>.
有关如何做到这一点的任何想法?
也许有人会纠正我,但我很确定你不会摆脱这种控制ng-options。当您使用它时,Angular 会在幕后为您管理选择,这在 90% 的情况下都很好,但在像您这样的情况下可能会受到限制。我不确定你在看什么基准,但我愿意打赌ng-repeat选项元素在性能上与使用ng-options.
我会用这样的东西:
<select ng-model="selectedExportType">
<option ng-repeat="exportType in exportTypes" data-generates-file="{{exportType.generatesFile}}" value="{{exportType.value}}">
{{exportType.title}}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
当然,这假设您确实需要该属性。如果您只需要在选择时访问该属性,那么这就是ng-options亮点。只需option.value as从您的选择中删除该位,然后在您进行选择时从您的阵列中取回整个对象。
http://plnkr.co/edit/6XPaficTbbzozSQqo6uE?p=preview
您可以在该演示中看到所选项目是整个对象,并带有someAttr从未在选择中使用过的属性。如果您检查 DOM,您将看不到它。Angular 在幕后跟踪这一切。
这里是一个可以用来使用时添加自定义属性的指令ng-options有<select>,这样就可以防止使用ng-repeat
.directive('optionsCustomAttr', function ($parse) {
return {
priority: 0,
require: 'ngModel',
link: function (scope, iElement, iAttrs) {
scope.addCustomAttr = function (attr, element, data, fnDisableIfTrue) {
$("option", element).each(function (i, e) {
var locals = {};
locals[attr] = data[i];
$(e).attr(iAttrs.customAttrName ? iAttrs.customAttrName : 'custom-attr', fnDisableIfTrue(scope, locals));
});
};
var expElements = iAttrs['optionsCustomAttr'].match(/(.+)\s+for\s+(.+)\s+in\s+(.+)/);
var attrToWatch = expElements[3];
var fnDisableIfTrue = $parse(expElements[1]);
scope.$watch(attrToWatch, function (newValue) {
if (newValue)
scope.addCustomAttr(expElements[2], iElement, newValue, fnDisableIfTrue);
});
}
};
})
Run Code Online (Sandbox Code Playgroud)
然后在你的选择中,
<select ng-model="selectedExportType" ng-options="option.value as option.title for option in exportTypes"
options-custom-attr="option.generatesFile for option in exportTypes"
custom-attr-name="data-generates-file">
</select>
Run Code Online (Sandbox Code Playgroud)
注意:这是此处optionsDisabled提到的目录的修改版本
| 归档时间: |
|
| 查看次数: |
8536 次 |
| 最近记录: |