gpt4 book ai didi

javascript - AngularJS 在 ngClass 更改后执行作用域函数

转载 作者:行者123 更新时间:2023-11-30 00:33:36 24 4
gpt4 key购买 nike

我的 AngularJS 元素中有以下设置:

Controller

app.controller('Controller', function ($scope, $timeout, someService) {

$scope.showItem = false;

$scope.show = function() {
$scope.showItem = true;
$scope.showCharts();
};

$scope.showCharts = function() {
// this code needs the HTML elements to have a width and height
console.log($('#chartContainer').width()); // prints always 0
};
}

查看

<div id="details" ng-class="{visible: showItem}">
<div id="chartContainer"></div>
</div>

CSS

#details {
opacity: 0;
transition: all .5s ease .25s;
}

#details.visible {
opacity: 1;
}

网站的特定部分仅在调用 Controller 方法时显示,否则它具有opacity: 0。 Controller 将 boolean 属性设置为 true(这将触发元素出现)。但是,在 $scope.showCharts(); 方法中,元素的宽度 始终为 0。唯一对我有用的是使用超时:

$timeout(function() {
$scope.showCharts(); // the width will be set now
}, 150);

当然,这是一个糟糕的解决方案。有谁知道一旦类发生变化并且 DOM 准备就绪,我如何调用作用域函数?

最佳答案

您可以在图表的宽度上放置一个$watch 并在它发生变化时执行您需要执行的任何操作。例如像这样的东西。

$scope.$watch(
function() {
return jQuery("#chartContainer").width();
},
function() {
// Do what you want when the size changes
}
);

关于javascript - AngularJS 在 ngClass 更改后执行作用域函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28217448/

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