发布
社区首页 >问答首页 >AngularJS -ng-当从指令注入时,重复不起作用

AngularJS -ng-当从指令注入时,重复不起作用
EN

Stack Overflow用户
提问于 2016-11-30 02:16:10
回答 1查看 155关注 0票数 0

我试图在一个指令中添加“在运行时”一个ng-repeat,当将相同的ng-repeat作为一个属性放在html中时,它不能工作,当从一个指令中添加时,它就不能了。请参阅下面的代码和插件。注意:这是一个非常简化的版本,但正如您所看到的,添加了行(我们有3行),但值显示为空。谢谢。

编辑:我简化了示例,以便从实验中删除更多可能的噪音……

获得的结果:

以ng-repeat作为属性的列表

单品: A001

单品: A002

单品: A003

带有ng重复注入的列表

项目:

项目:

项目:

Plunker

代码语言:javascript
代码运行次数:0
复制
<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>

EN

回答 1

Stack Overflow用户

发布于 2016-11-30 03:40:59

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

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

有关指令作用域here的更多信息

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40872923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档