1

私はAngularに不慣れで、いくつかのディレクティブをネストしようとしていますが、いくつかの問題があります。

これが私のコードです:

module.controller("TimelineController", ["$scope", "$compile", function ($scope, $compile) {

    $scope.text = "ohoh";
    $scope.elements = ["12", "13"];

    console.log("Timeline Controller", arguments);

}]);

module.directive('timeline', function() {
    return {
        restrict: 'E',
        transclude: true,
        scope: true,
        controller : "TimelineController",
        link: function(scope, element, attrs, controller) {
            console.log("linking timeline", arguments);
        },
        templateUrl:'templates/directives/timeline.html',
        replace: true
    };
});

module.directive('timelineEvent', function() {
    return {
        restrict: 'E',
        transclude: true,
        scope: true,
        // controller : "TimelineController",
        link: function(scope, element, attrs/*, controller*/) {
            console.log("linking element", arguments);
        },
        templateUrl:'templates/directives/timeline_element.html',
        replace: false
    };
});

私のテンプレート:

timeline.html:

<div class="timeline">
    <p>
        timeline {{text}}
    </p>

    <div ng-repeat="element in elements">
        - event {{element }}
        <timeline-event ng-model="{{element}}"/>
    </div>

</div>

timeline_element.html:

<div class="element">
    timeline element o/ \o
</div>

私のindex.html:

[...]
<body>

    <timeline></timeline>

</body>

そして予期しない結果:

timeline ohoh

- event 12
- event 13
timeline element o/ \o

もちろん、期待される結果は次のようになります。

timeline ohoh

- event 12
timeline element o/ \o
- event 13
timeline element o/ \o

ng-repeatが正常に実行されるのに、ネストされたディレクティブ呼び出しが1回だけ実行されるのはなぜですか?ループでディレクティブを使用できるはずではありませんか?

4

2 に答える 2

3

3 つのコメント。これらが原因かどうかはわかりませんが (そのためには jsFiddle でテストする必要があります)、確実に何かを壊しています:

  • なぜ設定するのtransclude: trueですか?ng-transcludeテンプレートでは使用しません。必要ありませんtransclude: true

  • ng-modelあなたのtimeline代わりelement{{element}}

  • を使用してscope: trueいます。つまり、新しいスコープが作成されます。scopeおそらく、(両方のディレクティブで) likeを定義する必要があります。

したがって:

scope: {
   element: '&' // provides a way to execute an expression in the context of the parent scope.
}
于 2013-01-09T18:09:14.460 に答える