4

選択入力フィールドを含むカスタム ディレクティブを作成しました。

私は ng-options を使用して選択オプションを設定しています。現在options、isolate スコープにバインドされた属性を使用して、オプションのデータを渡しています。下記参照。

<script>
  recManagerApp.directive(myDirective, function () {
    return {
      restrict: 'E',
      templateUrl: '/templates/directives/mydirective.html',
      scope: {
        mySelectedValue: "=",
        options : "="
      }
    };
  });
</script>

<my-directive my-selected-value="usersValue" options="myDataService.availbleOptions"></my-directive>

<div>
  <select data-ng-model="mySelectedValue" data-ng-options="item for item in options">
    <option value="">Select something</option>
  </select>
</div>

上記は期待どおりに機能し、オプションを正しく入力し、正しい値を選択し、親スコープのプロパティに双方向バインディングを行います。

ただし、my-directive 要素の属性を使用してオプションを渡すのではなく、ng-options のデータを提供できるサービス (myDataService) を挿入します。ただし、これを(さまざまな方法で)試してみると、サービスが正しく挿入され、データが利用可能であるにもかかわらず、オプションは作成されません。誰でもこれを行う方法を提案できますか?

recManagerApp.directive(myDirective, function (myDataService) {
    return {
        restrict: 'E',
        templateUrl: '/templates/directives/mydirective.html',
        scope: {
            mySelectedValue: "=",
            options : myDataService.availableOptions
        }
    };
});

ありがとう

マット

4

1 に答える 1

5

私の意見では、いくつかのオプションがあります(コメントで指摘されているように):

1. ディレクティブのコントローラーを作成する

ディレクティブのテンプレートで、コントローラーを使用します。

<div ng-controller="SelectController">
  <!-- your select with the ngOptions -->
</div>

SelectControllerを通常のコントローラーとして作成します。

var app = angular.module("app.controllers", [])

app.controller("SelectController", ['$scope', 'myDataService', function(scope, service) {
  scope.options = service.whatEverYourServiceDoesToProvideThis()
}]);

ディレクティブにコントローラーを与えることもできます。これはまったく同じように機能します。

recManagerApp.directive(myDirective, function () {
    return {
        restrict: 'E',
        templateUrl: '/templates/directives/mydirective.html',
        scope: {
            mySelectedValue: "=",
        },
        controller: ['$scope', 'myDataService', function(scope, service) {
          scope.options = service.whatEverYourServiceDoesToProvideThis()
        }]
    };
});

2.ディレクティブに挿入し、リンク内で使用する

recManagerApp.directive(myDirective, function (myDataService) {
    return {
        restrict: 'E',
        templateUrl: '/templates/directives/mydirective.html',
        scope: {
            mySelectedValue: "="
        },
        link: function(scope) {
          scope.options = myDataService.whatEverYourServiceDoesToProvideThis()
        }
    };
});
于 2013-08-06T08:58:12.413 に答える