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 回答