【问题标题】:AngularJS Dynamic Directives inside ng-repeatng-repeat 中的 AngularJS 动态指令
【发布时间】:2014-11-07 04:54:40
【问题描述】:

我正在尝试在 ng-repeat 中动态创建指令。我有一个directive-writer,它创建了许多其他指令,但directive-writer 似乎没有输出指令属性。所以第二组指令永远不会被渲染。

请参阅this Plunker 以获取完整演示。

总之我有这个指令标签:

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

范围数据:

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

指令定义:

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

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

还有 3 个类似的指令:

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

问题是directiveWriter 不会将tAttrs.directiveType 值作为属性写出,仅作为文本...

所以渲染出来的 HTML 是:

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

“三”在 div 内作为文本呈现没有问题,但从不作为属性呈现。

我不明白:

  • 为什么文本“三”可以作为文本绑定在 div 内,但不能作为属性。
  • 为什么类设置为“ng-binding”。

【问题讨论】:

    标签: angularjs angular-directive


    【解决方案1】:

    其中一个问题是属性解析为 html 的顺序。它们在周期的早期范围内可用这是一种方法:

    HTML:

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

    指令:

    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】:

    我修改了你的例子。现在它起作用了。你应该使用 $compile。

    看到这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      相关资源
      最近更新 更多