0

我是 angularjs 的新手,正在努力指示下拉菜单,但在选择初始值时遇到问题。我必须将要选择的选项的 ID 作为属性传递给指令。我在一个范围变量中设置属性值,然后在 ng-Init 中使用它。

这是我的指令代码:

export class ChoiceGroup
    {
        constructor ()
        {
            var directive: ng.IDirective = {};
            directive.restrict = "E";
            directive.replace = true;
            directive.template = '<div><select name="cmbCG" ng-model="dataSel" ng-options="c.DisplayName for c in data"></select></div>';
            directive.link = function ($scope: any, element: JQuery, attributes: any) {
                var injector = angular.element(document).injector();
                var key = attributes.key;

                var cgCacheService: ChoiceGroupsCacheService;
                seCGCacheService = injector.get('seChoiceGroupsCacheService');

                var values: Array<ChoiceValue>;
                values = seCGCacheService.GetChoiceValues(key);

                $scope.data = values;
                if (attributes.selectedvalue) {
                    $scope.selectedvalue = values[attributes.selectedvalue];
                }
            }

            return directive;
        }

代码在打字稿中。这是HTML:

<choicegroupcombo key="RecurrenceFrequency" selectedvalue="3"></choicegroupcombo>

如果我硬编码 dataSel 的值,即 ng-init="dataSel=3" 那么它工作正常但是当我设置为范围变量时它就不起作用了。那么我该如何解决这个问题。

编辑 解决。我已经相应地更新了代码。

4

1 回答 1

0

我认为这可能是“过度工程”的经典案例。

除了标准选择框所做的之外,您的代码似乎没有尝试做任何事情。

试试这个:

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

app.controller 'MainCtrl', ($scope) ->
  # $scope.values = ChoiceGroupsCacheService(key)
  $scope.values = [
    { id: 0, label: 'Zero' }
    { id: 1, label: 'One' }
    { id: 2, label: 'Two' }
    { id: 3, label: 'Three' }
  ]
  $scope.number = 2

和观点:

<select ng-model="number" ng-options="item.id as item.label for item in values"></select>

代码在咖啡脚本中:

这是一个 plunkr:http ://plnkr.co/edit/C6qmUoJ6HjsAT69oavRg

于 2013-11-27T15:14:43.773 回答