繁体   English   中英

使用angularjs中的指令在下拉菜单中选择一个选项

[英]Select an option in dropdown using a directive in angularjs

我是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;
        }

该代码在Typescript中。 这是HTML:

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

如果我对dataSel的值进行硬编码,即ng-init =“ dataSel = 3”,那么它可以正常工作,但是当我设置为范围变量时,它将不起作用。 那么我该如何解决该问题。

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

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

您的代码似乎没有尝试执行除标准选择框之外的任何操作。

尝试以下方法:

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>

代码在coffeescript中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM