我有一个指令,复制一些包含控制器和ng-repeat的html.我编译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); }; });
任何帮助将不胜感激.
解决方法
校验
http://plnkr.co/edit/l7o5EFC3863ZI4cxvuos?p=preview
更改以下内容
<div ng-controller="CopiedController" class="put-compiled-data-in-here" compile-html> app.directive('compileHtml',function($compile,$parse) { return { template: $('.copy').html(),restrict: 'A',link: function(scope,attrs) { // var html = jQuery('.copy').clone().removeClass('.blue').addClass('.pink'); // var el = angular.element(html); // ele.append(el); // $compile(ele.contents())(scope); ele.removeClass('blue').addClass('pink'); } }; });