考虑以下示例,其中一个元素静态包含在指令定义中,另一个元素稍后添加(使用 jQuery):
angular.module('test', []).directive('transcludeThis', [function () {
return {
restrict: 'E',
transclude: true,
replace: true,
template: '<div id="transcluded" data-ng-transclude></div>'
};
}]);
$(function() {
angular.bootstrap(document, ['test']);
$('#transcluded').append('<div>Dynamic (jQuery): </div>').find('*').each(function() {
var $this = $(this);
$this.append(angular.element($this).scope().$id);
});
});
<transclude-this>
<div>Static: </div>
</transclude-this>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://code.angularjs.org/1.3.10/angular.js"></script>
为什么动态元素不在嵌入范围内?
最佳答案
因为创建指令范围时动态元素不存在。如果您使用 Angular,您应该在指令内创建动态元素,然后范围将保持不变。
关于javascript - 如果在嵌入后添加动态元素,为什么指令下的动态元素会具有错误的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28574066/