gpt4 book ai didi

javascript - $document.ready 和 ng-model

转载 作者:行者123 更新时间:2023-11-28 19:40:26 25 4
gpt4 key购买 nike

我确实有一个指令,一旦文档准备好,我将尝试应用 Bootstrap 折叠功能。

为此,我必须浏览集合中的每个对象。

我的指令看起来像这样:

'use strict';

angular.module('app').directive("adScheduleTimeline",function($document) {
return {
restrict: 'E',
scope:{
ngModel: '='
},
templateUrl: '/partials/schedule/ad-schedule-timeline',
link: function (scope, el, attrs) {
scope.panelBaseId = attrs.collapsePanelBodyId;
scope.panelId = attrs.collapsePanelId;

$document.ready(function(){
console.log(scope.ngModel)
angular.forEach(scope.ngModel, function(value, key){
if (value.collapsed)
{
$("#" + scope.panelBaseId + "-" + key).collapse('show');
}
});
});
}
};
});

加载页面后,scope.ngModel未定义,因此collapse功能不起作用。有没有更好的方法在页面加载时实现类似的功能。

仅供引用,折叠函数来自 Bootstrap2.x.x。我没有使用 angular-ui-bootstrap。

最佳答案

您可以使用 scope.$watch() 等待 scope.ngModel 的值被填充。

link: function (scope, el, attrs) {
scope.panelBaseId = attrs.collapsePanelBodyId;
scope.panelId = attrs.collapsePanelId;

scope.$watch('ngModel', function (model) {
if (!model) { return; }

angular.forEach(model, function(value, key) {
if (value.collapsed) {
$("#" + scope.panelBaseId + "-" + key).collapse('show');
}
});
});
}

如果您只想执行一次,即稍后更改 scope.ngModel 时无需再次调用 collapse()。您可以像这样取消观看:

link: function (scope, el, attrs) {
scope.panelBaseId = attrs.collapsePanelBodyId;
scope.panelId = attrs.collapsePanelId;

var unwatch = scope.$watch('ngModel', function (model) {
if (!model) { return; }

unwatch();

angular.forEach(model, function(value, key) {
if (value.collapsed) {
$("#" + scope.panelBaseId + "-" + key).collapse('show');
}
});
});
}

顺便说一句,$document.ready()在这里没用, Angular 无论如何都会在开始 Bootstrap 之前等待文档准备好。

希望这有帮助。

关于javascript - $document.ready 和 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25182759/

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