-->

AngularJS Dynamic Directives inside ng-repeat

2019-06-02 01:28发布

问题:

I'm trying to create directives dynamically inside an ng-repeat. I have a directive-writer that creates a number of other directives but the directive-writer doesn't seem to output the directive attributes. So the second set of directives are never rendered.

See this Plunker for a full demo.

In short I have this directive tag:

<div ng-repeat="dir in directives" directive-writer 
     directive-text="{{ dir.text }}" directive-type="{{ dir.directive }}"></div>

Scope data:

$scope.directives = [
    { directive: 'one', text: 'I am One' },
    { directive: 'two', text: 'I am Two' },
    { directive: 'three', text: 'I am Three' }
];

Directive definition:

.directive('directiveWriter', function() {
    return {
        restrict: 'A',
        compile: function(tElement, tAttrs) {

            tElement.html('<div say="' + tAttrs.directiveText + '" '
                 + tAttrs.directiveType + '>' + tAttrs.directiveType + '</div>');
        }
    };

And 3 more directives all like this one:

.directive('one', function() {
    return {
        restrict: 'A',
        replace: true,
        template: '<h3 class="one"></h3>',
        compile: function(tElement, tAttrs) {
            tElement.text('One says, ' + tAttrs.say);
        }
    };

The problem is the directiveWriter doesn't write out the tAttrs.directiveType value as an attribute only as text...

So the rendered HTML is:

<div say="I am One" {{ dir.directive }} class="ng-binding">one</div>

Where "three" is rendered inside the div as text no problem but is never rendered as an attribute.

I don't understand:

  • Why the text "three" can be bound inside the div as text but not as an attribute.
  • Why the class is set to "ng-binding".

回答1:

One of the issues is order that attributes get resolved into html. They are available in scope earlier in the cycle Here's one way you can do it:

HTML:

<div directive-writer directive-text="dir.text" directive-type="dir.directive"></div>

Directive:

angular.module('app').directive('directiveWriter', function($compile) {
    return {
        restrict: 'A',
        scope:{
          directiveType:'=',
          directiveText:'='
        },
        link:function(scope,elem, attrs){
          var template='<div say="' + scope.directiveText + '" ' + scope.directiveType + '>' + scope.directiveType + '</div>';
          template= $compile(template)(scope);
          elem.replaceWith(template);
        }
    };
});

DEMO



回答2:

I modified your example. Now it works. You should use $compile.

See this

  (http://plnkr.co/edit/2pUzPClubLLBlfap8fhk?p=preview)