gpt4 book ai didi

javascript - ng-repeat 后 Angular 不更新 css

转载 作者:行者123 更新时间:2023-11-28 03:00:45 25 4
gpt4 key购买 nike

我在更新 Angular 元素的 CSS 时遇到问题。我有一个 div,其中包含 ng-repeat 生成的元素。包含这些元素的 div 具有设置的高度,并附加了 ng-scrollbars 指令。当 div 中的元素超过其容器的高度时,ng-scrollbarsdiv 中创建一个漂亮的滚动条。为此,它会创建嵌套的内部 div。因此,在这种情况下,如果嵌套的内部 div 的高度大于它们的容器,则会制作一个滚动条,以便您可以滚动元素。

假设我在 ng-repeat 列表中添加或删除元素。发生这种情况时,我希望将额外的 css 添加到顶级 div 只有当ng-scrollbars 制作的内部 div 超过顶级 div 的高度时。 (内部 div 的高度是 ng-repeat 列表的实际高度,因为它包含 ng-repeat 元素)

为此,我创建了两个指令,一个广播事件,一个接收事件。广播事件的事件附加到每个 ng-repeat 元素,并在创建或销毁元素时广播。这是为了检查 ng-repeat 列表何时发生更改。

接收广播的那个附加到顶层div 容器(包含ng-scrollbar 制作的div 的容器)并根据ng-scrollbar制作的内部div,如果内部div的高度大于顶层div,则添加一些css。

如果这看起来令人困惑,我很抱歉,这是我的代码,附有评论,我希望能更好地解释它:

app.directive('gtScrollLb', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) { //elem is the top level container of the ng-repeat elements
var scrollDiv = elem.children()[0]; //this is an internal div created by ng-scrollbars
var anotherScrollDiv = $(scrollDiv).children("#" + $(scrollDiv).attr("id") + "_container"); //another internal div created by ng-scrollbars
var id = attrs.gtScrollLb;

scope.$on(id + "-repeat-change",
function(newVal, oldVal) {
//check if ng-scrollbar div that now contains the ng-repeat elements
//has a greater height than the top level container
if ($(anotherScrollDiv).height() >= elem.height()) {
elem.css("border-bottom", "1px solid darkgrey");
} else {
elem.css("border-bottom", "");
}
}
);
}
};
});

app.directive('gtRepeatable', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var id = attrs.gtRepeatable;
scope.$emit(id + "-repeat-change"); //event that item has been added by ng-repeat
var parent = scope.$parent;
elem.bind("$destroy",function(){
parent.$broadcast(id + "-repeat-change");//event that item has been destroyed by ng-repeat
});
}
}
});

问题是 ng-repeat 元素在 再次确定其内部容器的高度之前被添加和销毁。因此,触发更改事件时检查的高度实际上是内部容器的旧高度。

我需要以某种方式检查新高度。很长一段时间以来,我一直在努力解决这个问题,我们将不胜感激任何帮助。

编辑

简而言之,在 ng-repeat 完成且 DOM 呈现后,我需要一个偶数触发或 $watch 发生。我在这里遇到的问题只是因为事件在 DOM 呈现之前触发。

编辑2

@vittore 将其标记为重复项。如果您实际上已经详细阅读了我的问题,您会发现您提出的重复问题与我的实际问题无关。这里用ng-scrollbars是没有问题的。 ng-scrollbars 工作正常。但有必要将其包含在描述中,因为它会影响我解决问题的方式。

最佳答案

有一种方法可以在呈现最后一个循环元素时获取事件。检查此链接:AngularJS - Manipulating the DOM after ng-repeat is finished

这也是您的确切问题:ng-scrollbar is not working with ng-repeat

重要的部分:

  $scope.$on('loopLoaded', function(evt, index) {
if (index == $scope.me.length-1) {
$scope.$broadcast('rebuild:me');
}
});

关于javascript - ng-repeat 后 Angular 不更新 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34796110/

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