如何转换为属性?

Jak*_*old 25 angularjs

有可能以某种方式使用ngTransclude属性值,而不是替换内部HTML内容?例如这个简单的指令

var testapp = angular.module('testapp', [])

testapp.directive('tag', function() {
  return {
    template: '<h1><a href="{{transcludeHere}}" ng-transclude></a></h1>',
    restrict: 'E',
    transclude: true
  }
});
Run Code Online (Sandbox Code Playgroud)

并用它作为

<tag>foo</tag>
Run Code Online (Sandbox Code Playgroud)

我想把它翻译成

<h1><a href="foo">foo</a></h1>
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点,还是我必须使用属性而不是转录?

这是一个例子

Art*_*eev 24

像这样的东西:

var testapp = angular.module('testapp', [])

testapp.directive('tag', function() {
  return {
    restrict: 'E',
    template: '<h1><a href="{{transcluded_content}}">{{transcluded_content}}</a></h1>',
    replace: true,
    transclude: true,
    compile: function compile(tElement, tAttrs, transclude) {
        return {
            pre: function(scope) {
                transclude(scope, function(clone) {
                  scope.transcluded_content = clone[0].textContent;
                });
            }
        }
    }
  }
});?
Run Code Online (Sandbox Code Playgroud)

小提琴.


Vad*_*dim 7

还有一个解决方案

app.directive('tag', function($compile) {
  return {
    restrict: 'E',
    template:"<h1></h1>",
    transclude: 'element',
    replace: true,
    controller: function($scope, $element, $transclude) {
      $transclude(function(clone) {
        var a = angular.element('<a>');
        a.attr('href', clone.text());
        a.text(clone.text());        
        // If you wish to use ng directives in your <a>
        // it should be compiled
        //a.attr('ng-click', "click()");
        //$compile(a)($scope);       
        $element.append(a);
      });
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

Plunker:http://plnkr.co/edit/0ZfeLz?p = preview

  • 如果控制器内没有DOM操作,这将是一个更好的答案 (2认同)
  • @georgiosd - > DOM操作正是ngTransclude指令本身所做的. (2认同)