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

コードは Typescript です。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>

コードはcoffeescriptにあります:

ここに plunkr があります: http://plnkr.co/edit/C6qmUoJ6HjsAT69oavRg

于 2013-11-27T15:14:43.773 に答える