【问题标题】:AngularJS - ng-repeat not working when injected from a directiveAngularJS - 从指令注入时 ng-repeat 不起作用
【发布时间】:2016-12-01 03:38:53
【问题描述】:

我正在尝试在指令中添加“在运行时”一个 ng-repeat,虽然将相同的 ng-repeat 作为属性放在 html 中时可以工作,但从指令中添加时却不起作用。请参阅下面的代码和 pluker。注意:这是一个非常简化的版本,但正如您所见,添加了行(我们 wee 3 行),但值显示为空。谢谢。

编辑:我简化了示例以从实验中消除更多可能的噪音...

得到的结果:

以 ng-repeat 作为属性的列表

项目:A001

项目:A002

项目:A003

注入 ng-repeat 的列表

项目:

项目:

项目:

Plunker

<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


【解决方案1】:

在指令定义对象中使用属性scope : {} 时,它会创建一个新范围。所以rlfList 不是这个新范围的一部分。

更改为scope:false,以便指令使用其父范围。

有关指令范围的更多信息here

【讨论】:

  • 如果范围无效,将无法统计和显示 3 行。不 ?我的意思是,它就像它可以计算和显示行,但不能访问每个对象的属性。尽管如此,我还是尝试了您所说的,结果是样式不起作用(请参阅新的 plunker:embed.plnkr.co/UsARAo2h95aZj7p0Wdvv)。谢谢
  • 删除 disabled-for-test-ng-repeat="item in rlfList.lists['listOne'].records" 并查看结果。顺便说一句,disabled-for-test-ng-repeat 是干什么用的?
  • 关于disabled-for-test-ng-repeat="的好点...这是为了测试目的,但它实际上做错了什么...但是它仍然没有' t 工作!查看我最初的问题,我对其进行了编辑/简化并删除了任何不需要的内容并更新了 plunker。
猜你喜欢
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 2018-09-07
  • 2014-03-10
相关资源
最近更新 更多