我试图在一个指令中添加“在运行时”一个ng-repeat,当将相同的ng-repeat作为一个属性放在html中时,它不能工作,当从一个指令中添加时,它就不能了。请参阅下面的代码和插件。注意:这是一个非常简化的版本,但正如您所看到的,添加了行(我们有3行),但值显示为空。谢谢。
编辑:我简化了示例,以便从实验中删除更多可能的噪音……
获得的结果:
以ng-repeat作为属性的列表
单品: A001
单品: A002
单品: A003
带有ng重复注入的列表
项目:
项目:
项目:
<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>
发布于 2016-11-30 03:40:59
当在指令定义对象中使用属性scope : {}
时,它会创建一个新的作用域。所以rlfList
不是新作用域的一部分。
更改为scope:false
,以便指令使用其父作用域。
有关指令作用域here的更多信息
https://stackoverflow.com/questions/40872923
复制相似问题