我仍在学习 AngularJS。
我在用于加载 Angular 对象的 JS 文件中有以下函数:
app.controller("myController", ['$scope', '$compile', function ($scope, $compile) {
var $theContainer = $('.container123');
...
this.loadStuff = function () {
$compile('<layout-withbars></layout-withbars>')($scope, function (clonedElement, $scope) {
$theContainer.html(clonedElement); // **this line is where my tests show a runtime issue **
setTimeout(function () {
$('.progress-bar').each(function () {
var $bar = $(this);
$bar.css('width', $bar.attr('aria-valuenow') + '%');
});
}, 1500);
});
};
}]);
指令本身正确加载,它包含 Bootstrap 进度条。此“loadStuff”函数的目标是加载指令,然后使用默认 Bootstrap 转换使进度条从 0% 更改为 X% 完成。
如果我在页面上调用此 block ( block 1),它会触发我需要的行为:
$('.progress-bar').each(function () {
var $bar = $(this);
$bar.css('width', $bar.attr('aria-valuenow') + '%');
});
layout-withbars.html:
<div ng-repeat="aProgressbar in progressbars" class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="{{aProgressbar.complete}}" style="width: 0%;">
</div>
</div>
问题:
我必须在 Controller 调用周围附加一个“setTimeout”函数到 block 1。我这样做是因为经过一些测试,我相信 $compile 服务指令注入(inject)/处理在调用所描述的 block 1 后完成执行。我在上面的代码中突出显示了它。
有没有办法在这里组织执行时间?在某些情况下,我的 1.5 秒延迟可能还不够。
我正在寻找 $compile 服务的回调函数。我相信它是“postLink”。我尝试实现它,但还没有成功。
$compile 服务指令注入(inject)/处理完成执行后,发出 block 1 执行的最佳方式是什么?
顺便说一句,我也在 block 1 周围尝试过这个,但没有成功:
$theContainer.html(clonedElement).promise().done(function(){
...
}
最佳答案
是的,我坚持删除无意义的 Jquery 代码和 $compile
的错误使用。因此不需要带有超时的回调函数。
无需手动告诉 Angular 编译该指令,可以通过 ng-if 让它出现在 DOM 中。当要从 DOM 中动态添加或删除的指令数量有限(您的情况是一个)时,这非常适合这种情况。
<layout-withbars ng-if="showProgress"></layout-withbars>
所以 loadStuff
应该只设置 $scope.showProgress = true;
请记住,与 ng-show
相反,ng-if
实际上会在表达式为 falsy
时删除元素。因此,每次它变为 truthy
并将元素添加到 DOM 时,指令都会再次链接。指令的 link
(或实际上 postLink
)处理程序中的结论与您试图在 setTimeout()
中实现的处理程序完全相同。然而,这将不再需要,因为有一个指令允许对元素的样式进行数据绑定(bind)。
<div class="progress-bar"
role="progressbar"
ng-style="{width: aProgressbar.complete + '%';">
这样,一旦模型中的数据更新,宽度就会更新。
关于javascript - 如何将回调函数传递给 angularJS Controller 中的 $compile 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31867713/