gpt4 book ai didi

angularjs - ng-repeat 在编译 html 后不加载数据

转载 作者:行者123 更新时间:2023-12-03 07:01:09 25 4
gpt4 key购买 nike

我有一个指令,它复制一些 html,其中包括一个 Controller 和一个 ng-repeat。我编译了 html 并将其粘贴到 dom 中。我可以看到新的 html 正在获取新编译的 Controller 的范围,但如果数据异步加载,ng-repeat 将不起作用。

我创建了一个笨蛋 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>

Controller

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, $rootScope, $parse) {
return {
template: $('.copy').html(),
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);
ele.removeClass('blue').addClass('pink');
}
};
});

关于angularjs - ng-repeat 在编译 html 后不加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19782729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com