0

次のディレクティブを想定します。

<validation-errors field="someField">Some errors: {{errors}}</validation-errors>

次のように簡単なディレクティブ関数を作成できると思いました。

    return {
        require: '^form',
        restrict: 'E',
        link: link,
        scope: {
            field: '@'
        },
        transclude: true,
        template: '<span ng-show="errors" class="alert-danger" ng-transclude></span>'
    };

    function link(scope, el, attr, ctrl, transcludeFn) {
        scope.errors = ctrl.Validator.getErrors(attr.field);
    }

しかし、Transclusion is the process of extracting a collection of DOM element from one part of the DOM and copying them to another part of the DOM, while maintaining their connection to the original AngularJS scope from where they were taken.(ドキュメントから)以来、スコープは思ったように機能しません。

だから私はこれを試しましたが、「いくつかのエラー」の部分が重複していることを除いて:

transcludeFn(function(clone, transScope) {
    scope.errors = transScope.errors = ctrl.Validator.getErrors(attr.field);
    el.append(clone);
});

を外すとうまくいきませんel.append(clone);

トランスクルージョンされたコンテンツがディレクティブ テンプレートのスコープを共有するようにする最善の方法は何ですか?

4

1 に答える 1

0

ディレクティブを使用してエラーを作成する場合は、このようなものを試してみてください。コードを更新して、テンプレートもコンパイルするようにしました。これで、ng-transcludeディレクティブがそのまま使用できるようになりました。

'use strict';

/* Directives */

angular.module('myApp.directives', []).
directive('errordirective', ['$compile',function($compile) {
  return {
    restrict: 'E',
    scope: {
      field: '@',
    },
    transclude: true,
    //Create some error text
    controller: function() {
      this.errorText = "Some Errors We Created";
      //Make the template available to the link fn, and make it an angular element.
      this.template = angular.element('<span class="alert-danger" ng-transclude></span>')
    },
    //Make the controller available easily
    controllerAs: 'Errors',
    //Bind the scope properties to the controller, only works with controllerAs
    bindToController: true,
    template: '<span class="alert-danger" ng-transclude></span>',
    link: function(scope, elem, attrs, ctrl, transcludefn) {
      //Replace the original element with the new one that has the error text from our controller
      transcludefn(scope, function(el) {
        var template = ctrl.template;
        var html = el.html();
        //Add the transcluded content to the template
        template.html(html);
        //Compile the template with the appropriate scope
        template = $compile(template)(scope);
        //Replace with the new template
        elem.replaceWith(template);

      });
    }

  };
}]);
于 2015-07-10T16:53:20.323 に答える