【发布时间】:2013-11-05 05:53:26
【问题描述】:
我有一个指令,它复制了一些 html,其中包括一个控制器和一个 ng-repeat。我编译 html 并将其粘贴到 dom 中。我可以看到新的 html 正在获取新编译的控制器的范围,但是如果数据是异步加载的,那么 ng-repeat 将不起作用。
我创建了一个 plunker http://plnkr.co/edit/jCjW26PCwlmKVTohja0s?p=preview,它显示了我遇到的问题。
index.html
<div class="parent-div">
<div class="put-compiled-data-in-here" compile-html>
<!-- copied html goes in here -->
</div>
<div ng-controller="CopiedController" class="copy blue">
<h1>{{name}}</h1>
<div ng-repeat="p in projects">
<h1>{{p.name}}</h1>
</div>
</div>
</div>
控制器
app.controller('CopiedController', function($scope, slowService){
$scope.projects = slowService.loadSlowData();
$scope.name = "Inside Copied Controller";
});
复制和编译html的指令
app.directive('compileHtml', function ($compile, $rootScope, $parse) {
return {
restrict: 'A',
link: function (scope, ele, attrs) {
var html = jQuery('.copy').clone().removeClass('.blue').addClass('.pink');
var el = angular.element(html);
ele.append(el);
$compile(ele.contents())(scope);
}
};
});
慢速服务(又名 ajax):
app.service('slowService', function($timeout) {
this.loadSlowData = function() {
return $timeout(function() {
return [{name:"Part 2a"},
{name:"Part 2b" } ]
}, 300);
};
});
任何帮助将不胜感激。
【问题讨论】:
-
您是否真的希望复制的部分再次加载数据,这就像您正在尝试做的那样?还是只想在页面的两个不同位置显示相同的数据?如果是后者,那么您应该将数据放在范围内,以便双方都能看到它。也许使用共享服务。
-
在克隆上操作类有什么意义......然后只使用它的内部html?使用
ng-class
标签: angularjs angularjs-directive angularjs-ng-repeat