动态渲染Angular指令中的选择选项并转换默认选项

时间:2014-08-14 19:34:29

标签: angularjs angularjs-directive

我有一个外部RESTful数据源,用于在各种选择框中创建选项,如下所示:

<div data-ng-app="app">
    <custom-select ng-model="selectedValue" option-source="myCodes">
        <option value="">ALL</option>
    </custom-select>
</div>

我编写了一个能够成功执行查找并填充下拉列表的指令

var app = angular.module('app', []);

app.directive('customSelect', function ($compile) {
   return {
     transclude: true,
     scope: {
         optionSource: '@'
     },
     restrict: "E",
     template: '<select ng-options="value.longName for value in codes" ng-transclude></select>',
     replace: true,
     link: function (scope, element) {
         //Note: This would be a lookup, I'll just set the results
         scope.codes = [{
             "id": "F",
                 "shortName": "F",
                 "name": "FOREIGN MOVE",
                 "longName": "Foreign"
         }, {
             "id": "C",
                 "shortName": "C",
                 "name": "COAL",
                 "longName": "Coal"
         }, {
             "id": "D",
                 "shortName": "D",
                 "name": "DUMMY SCHEDULES",
                 "longName": "Dummy Schedule"
         }];
     }
   };
});

我无法做的是允许指令的用户在指令标签的主体中传递默认选项,而不使用Angular添加默认的&#34;空白&#34;选择。 Here is a fiddle demonstrating the problem

1 个答案:

答案 0 :(得分:0)

我宁愿把所有内容都放在option-source中。我在ng-options之后添加选项标签时遇到了问题。