我正在尝试在另一个指令中呈现一个指令(不确定模板内的中继器是否在工作),它似乎只是作为文本输出而不是编译指令(柱塞代码在这里:http://plnkr.co/edit/IRsNK9)。
我有什么想法可以让它在中继器内正确地呈现我的-dir-1,我的-dir-2,我的-dir-3指令?
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>'
}
});发布于 2013-05-13 09:47:59
通过重写代码,我设法解决了这个问题:
首先我更新了模板代码如下:
template: '<div class="views">' +
' <div class="view-wrapper" ng-repeat="view in views">' +
' <div view="{{view.dir}}"></div>' +
' </div>' +
'</div>',注意到我创建了一个新的“视图”指令。接下来,视图指令定义如下:
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‘指令,后者监视它的值,并编译一个包含该指令的模板。
发布于 2013-05-10 15:15:14
这在一定程度上是一个时间问题.我认为当它解决{{}}表达式时,它已经被解析并呈现了指令。问题不在于嵌套或中继器本身。
不过,这里您想要的是“根据变量的值来决定呈现哪个指令”。有几种方法可以做到这一点。
这里有一个应该有效的方法,尽管它可能没有您想要的那么好:
<div class='views' ng-repeat='view in views'>
<div ng-switch='view.dir'>
<div ng-when='my-dir-one' my-dir-one />
<div ng-when='my-dir-two' my-dir-two />
<div ng-when='my-dire-three' my-dir-three />
</div>
</div>类似技巧的其他选项:看起来您可以使用ngBindTemplate从数据中提取字符串,并将其用作元素的模板。这可能会导致一些棘手的(和难以辨认的)行为。
您可以将元素的指令指定为类,但我不知道使用ngClass来执行此操作是否允许动态选择指令,或者在执行过程中是否为时已晚。
https://stackoverflow.com/questions/16479162
复制相似问题