gpt4 book ai didi

angularjs - 在 ngInclude 中使用 ngTransclude

转载 作者:行者123 更新时间:2023-12-02 05:17:07 25 4
gpt4 key购买 nike

我不能在模板中使用 ng-transclude 指令。我收到以下错误:

Error: [ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element:

<script type="text/ng-template" id="item.html">
<div ng-transclude>
</div>
</script>


<div ng-include="'item.html'"></div>

最佳答案

ng-include 使用 element transclusion 而不是 content transclusion,所以这是行不通的。

describe('element transclusion', function() {

it('should support basic element transclusion', function() {
module(function() {
directive('trans', function(log) {
return {
transclude: 'element',
priority: 2,
controller: function($transclude) { this.$transclude = $transclude; },
compile: function(element, attrs, template) {
log('compile: ' + angular.mock.dump(element));
return function(scope, element, attrs, ctrl) {
log('link');
var cursor = element;
template(scope.$new(), function(clone) {cursor.after(cursor = clone);});
ctrl.$transclude(function(clone) {cursor.after(clone);});
};
}
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div><div high-log trans="text" log>{{$parent.$id}}-{{$id}};</div></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('compile: <!-- trans: text -->; link; LOG; LOG; HIGH');
expect(element.text()).toEqual('1-2;1-3;');
});
});

When we specify the transclude: 'element' option we cannot use a template, so we cannot even specify where to put the transcluded element with the ng-transclude attribute.

使用装饰器来代替content transclusion:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="transcludeExample">
<script type="text/ng-template" id="foo">
</script>

<script>
function delegator($delegate)
{
/* Override transclude configuration */
$delegate[0].transclude = true;

return $delegate;
}


function provider($provide)
{
/* Deocrate ng-include with a proxy function */
$provide.decorator('ngIncludeDirective', ["$delegate", delegator]);
}

/* Inject the provider and the delegator methods with services */
provider['$inject'] = ['$provide'];
delegator['$inject'] = ['$delegate'];

/* Inject the module with the new provider */
angular.module('transcludeExample', []);
angular.module("transcludeExample").config(["$provide",provider]);
</script>

<div>Non-transcluded ID: {{$id}}</div><div ng-include src="'foo'" data-foo="{{$id}}">Transcluded ID: {{$id}}<ng-transclude></div></div>
</body>

内容嵌入定义如下:

allowing a directive to wrap arbitrary child content inside additional template HTML.

而元素嵌入意味着:

the template we pass in to the directive will replace the element with ng-transclude directive.

引用资料

关于angularjs - 在 ngInclude 中使用 ngTransclude,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32202170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com