4

考虑以下代码(http://jsbin.com/IfejIWES/1/):

HTML:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.3/angular.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <div ng-controller="MyCtrl">

    <div my-directive>
        <button>some button</button>
        <a href="#">and a link</a>
    </div>
</div>
</body>
</html>

JS:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    //$scope.log=[];   
}

myApp.directive('myDirective', function(){
    return{
        transclude: true,
        template: '<div class="something" ng-transclude> This is my directive content</div>'
    };
});

使用AngularJS 的1.1.3版本,输出my-directive(在 HTML 中)中的按钮和锚点与模板内部文本“这是我的指令内容”结合在一起。

如果我将版本更改为1.2.1,my-directive 内容将替换模板内部文本。

有没有办法让 angular 1.2.1(及更高版本)执行较旧的行为?

4

2 回答 2

1

不,这是一个非常有意的改变。请参阅此提交

于 2014-01-07T20:47:38.703 回答
0

Jeff Hubbard(感谢 Jeff)提供的链接让我朝着正确的方向前进。从该帖子的评论中,有人(https://github.com/angular/angular.js/commit/eed299a31b5a6dd0363133c5f9271bf33d090c94#commitcomment-4685184)发布了一个解决方法:http ://plnkr.co/edit/EjO8SpUT91PuXP0RMuJx?p=preview

本质上,您可以通过更改 JavaScript 以在单独的指令中使用 transcludeFn 函数来恢复旧行为。请参阅下面我更新的代码:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {

}

myApp.directive('myDirective', function(){
    return{
        transclude: true,
        template: '<div class="something" ng-transclude-append> This is my directive content</div>'      
    };
});

myApp.directive('ngTranscludeAppend', function() {
  return function(scope, element, attrs, ctrl, transcludeFn) {
      if (!transcludeFn) return;

      transcludeFn(function(clone) {
        element.append(clone);
      });
    };
});

链接到我更新的 jsbin:http: //jsbin.com/IfejIWES/3/

最后一点,我尝试将 transcludeFn 直接嵌入到我的链接函数中,例如:

link: function(scope, element, attrs, ctrl, transcludeFn) {          
  transcludeFn(function(clone) {
    element.append(clone);
  });
}

但这会产生两次创建按钮和锚点的效果。将它移到它自己的指令中为我解决了它。

于 2014-01-07T21:17:21.890 回答