【发布时间】:2016-12-01 03:38:53
【问题描述】:
我正在尝试在指令中添加“在运行时”一个 ng-repeat,虽然将相同的 ng-repeat 作为属性放在 html 中时可以工作,但从指令中添加时却不起作用。请参阅下面的代码和 pluker。注意:这是一个非常简化的版本,但正如您所见,添加了行(我们 wee 3 行),但值显示为空。谢谢。
编辑:我简化了示例以从实验中消除更多可能的噪音...
得到的结果:
以 ng-repeat 作为属性的列表
项目:A001
项目:A002
项目:A003
注入 ng-repeat 的列表
项目:
项目:
项目:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript">
angular.module('rlfList', []);
angular.module('rlfList').directive('rlfItem', ['$compile', function ($compile) {
return {
restrict: 'EA',
scope: false,
link: function link(scope, element, attrs) {
if (!element.hasClass('rlfListRow')) {
element.addClass('rlfListRow');
element.attr('ng-repeat', 'item in records');
$compile(element)(scope);
}
}
};
}]);
angular.module('rlfList').controller('rlfController', ['$scope', '$timeout', function ($scope, $timeout) {
$scope.records = [];
$scope.records[0] = { number: 'A001' };
$scope.records[1] = { number: 'A002' };
$scope.records[2] = { number: 'A003' };
}]);
</script>
<div ng-app="rlfList" ng-controller="rlfController">
<div style="margin-top: 20px;">LIST with ng-repeat as attribute</div>
<div ng-repeat="item in records"><span>ITEM : {{ item.number }}</span></div>
<div style="margin-top: 20px;">LIST with ng-repeat injected</div>
<div rlf-item><span>ITEM : {{ item.number }}</span></div>
</div>
【问题讨论】:
-
我认为它是按需要编译的,但元素永远不会被替换。这可能是它不起作用的原因..
标签: angularjs angularjs-ng-repeat