gpt4 book ai didi

angularjs - 在另一个指令中渲染一个指令(在转发器模板中)

转载 作者:行者123 更新时间:2023-12-04 11:39:56 24 4
gpt4 key购买 nike

我试图在另一个指令中呈现一个指令(不确定模板中的转发器是否正在工作),它似乎只是作为文本输出而不是编译指令(此处的plunker代码:http://plnkr.co/edit/IRsNK9)

关于如何真正让它在中继器内正确呈现 my-dir-one、my-dir-2、my-dir-three 指令的任何想法?

index.html

<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.js"></script>
<script src="app.js"></script>
<script id="partials/addressform.html" type="text/ng-template">
partial of type {{type}}<br>
</script>
</head>
<body>
<div container></div>

<br /><br /><br />
<b>Below is just to test the directives are actually usable outside the repeater</b>
<div my-dir-one></div>
<div my-dir-two></div>
<div my-dir-three></div>
</body>
</html>

app.js
var app = angular.module('plunker', []);

app.directive('container', function () {

return {
restrict: 'A',
scope: {},
replace: true,

template: '<div class="views">' +
' <div class="view" ng-repeat="view in views">' +
' <div {{view.dir}}>{{view.dir}}</div>' +
' </div>' +
'</div>',

link: function (scope, elm) {

scope.views = [
{ dir: 'my-dir-one' },
{ dir: 'my-dir-two' },
{ dir: 'my-dir-three' }
];
}
}
});

app.directive('myDirOne', function () {
return {
restrict: 'A',
scope: {},
replace: true,
template: '<div>This is directive one.</div>'
}
});

app.directive('myDirTwo', function () {
return {
restrict: 'A',
scope: {},
replace: true,
template: '<div>This is directive two.</div>'
}
});

app.directive('myDirThree', function () {
return {
restrict: 'A',
scope: {},
replace: true,
template: '<div>This is directive three.</div>'
}
});

最佳答案

我设法通过重新编写代码解决了这个问题:

首先我更新了模板代码如下:

template: '<div class="views">' +
' <div class="view-wrapper" ng-repeat="view in views">' +
' <div view="{{view.dir}}"></div>' +
' </div>' +
'</div>',

请注意,我创建了一个新的“ View ”指令。接下来 View 指令定义如下:
app.directive('view', ['$compile', function (compile) {

return {
restrict: 'A',
scope: {
view: '@'
},
replace: true,
template: '<div class="view"></div>',

controller: ['$scope', function (scope) {
scope.$watch('view', function (value) {
scope.buildView(value);
});
}],

link: function (scope, elm, attrs) {

scope.buildView = function (viewName) {
var view = compile('<div ' + viewName + '></div>')(scope);
elm.append(view);
}
}
}
}]);

所以本质上,view.dir 变量作为属性传递给 'view' 指令,然后该指令观察它的值并编译包含该指令的模板。

关于angularjs - 在另一个指令中渲染一个指令(在转发器模板中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16479162/

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