AngularJS NG重复内的动态指令指令、动态、AngularJS、NG

由网友(如ァ美人残)分享简介:我试图动态创建一个NG重复内部指令。我有一个指令作家创建了一些其他指令,但指令作家似乎没有输出的不该指令属性。所以,第二组指令不会被渲染。I'm trying to create directives dynamically inside an ng-repeat. I have a directive-write...

我试图动态创建一个NG重复内部指令。我有一个指令作家创建了一些其他指令,但指令作家似乎没有输出的不该指令属性。所以,第二组指令不会被渲染。

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.

请参阅一个完整的演示这个Plunker 。

总之我有这个指令标记:

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.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个指令,所有像这样的:

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);
        }
    };

问题是 directiveWriter 不写出来的 tAttrs.directiveType 值只作为文本属性...

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

所以呈现的HTML是:

So the rendered HTML is:

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

其中,三化呈现在div文字没有问题,但里面永远不会呈现为一个属性。

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

我不明白:

为什么文本三化,可以在div的文本中而不是作为一个属性的约束。为什么类设置为NG结合。

推荐答案

的问题之一是为了使属性得到解决成html。他们在早些时候周期范围内可用这里有一种方法可以做到这一点:

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>

指令:

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);
        }
    };
});

演示

阅读全文

相关推荐

最新文章