0

これまでのところ、私の AngularJS はすべて 1 つのページにあり、1 つのコントローラー内にあります。ここで、6 ページすべて (現在コントローラーがない 5 ページと、現在 "FoodCtrl" がある 1 ページ) にわたってツールヒントを動的に表示する方法を構築する必要があります。私が構築している関数は、tooltips.json ファイルから読み取り、id によってこのページの正しいツールヒントを見つけ、ツールヒントのコンテンツを DOM に挿入します。

myApp は、これらすべてのページで既に初期化されています。次のように、小さくフラットな階層構造です。

--> Profile
--> Information
--> Test (has controller FoodCtrl)
--> Payment

ここで正しい Angular の実践に関するアドバイスを探しています。「FoodCtrl」を目的のツールチップ動作で拡張し、サイト内の他のページに「FoodCtrl」コントローラーを追加する必要がありますか? または、すべてのページに独自の「Tooltips」コントローラーを作成し、これを既に「FoodCtrl」があるページに統合する必要がありますか? または、一般的なツールチップ ファクトリ/サービスを設定し、これを "FoodCtrl" および他のページの新しい特定のコントローラーから参照する必要がありますか?

4

2 に答える 2

2

外部ソースから情報を取得するメカニズムは、個別のサービスに抽出し、必要に応じて挿入する必要があります。
役立つリンク
http://docs.angularjs.org/guide/dev_guide.services.creating_services
http://docs.angularjs.org/guide/dev_guide.services.injecting_controllers

サービス利用例

var app = angular.module('myApp', []);
app.service('tooltips', function() {
  this.getTooptip = function(pageId) {
      ...
  };
});

function myController($scope, tooltips) {
  $scope.pageId = '<pageID>'
    $scope.tooltip = tooltips.getTooltip($scope.pageId);
}
于 2013-11-14T11:36:32.483 に答える
0

はい、コントローラーを使用してページでこれまですべての AngularJS を実行してきたので、コントローラーが宣言されていないページでディレクティブが機能するかどうかについて混乱していました。回答: ng-app が実行されている限り、確実に実行されます。そこで、ツールチップを必要とする各ページのラッピング div にツールチップを追加し、ツールチップを呼び出しているページを特定するためのツールチップというディレクティブを作成し、サービスを使用してデータをロードしました。

HTML:

<div class="pagewrapper" tooltip data-title="unique-page-title">

JSON:

[{
    "extension": "unique-page-title",
    "contents": [
        {
            "head": "Tooltip heading one",
            "content": "information on section 1"
        },
        {
            "head": "Tooltip heading two",
            "content": "information on section 2"
        }
    ]
}]

JS:

angular.module('myApp.services', []).service('tooltips', function ($http) {
        var requestPromise = $http.get('path/to/tooltips.json').then(function (d) {
            return d.data;
        });
        this.getTooltips = function () {
            return requestPromise;
        };
});

angular.module('myApp.directives', []).directive('tooltip', function (tooltips, $filter) {
        return {
            restrict: 'A',
            link: function (scope, element, attr) {
                var elements = $('.forms .tooltip'),
                    list = [],
                    title = attr.title;

                //use the promisey service getTooltips to load the tooltips JSON
                tooltips.getTooltips().then(function (tips) {
                    //Do some things to identify the correct place to insert the tooltip content, and insert it.
                });
            }
        };
    });
于 2013-11-14T17:57:11.193 に答える