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

标签 javascript css angularjs

我的 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/

相关文章:

javascript - 仿谷歌地图mapTypeControl自定义控件

css - 是否可以使用 CSS 网格布局创建正方形网格?

css 工具提示中的 php 文本

javascript - angularjs 中 ng-repeat 和 collection-repeat 的区别?

javascript - 如何使用 Angular 访问嵌套的 JSON 数组数据,并按数组参数过滤?

angularjs - 如何调试空白页错误(由 UI-Router 引起)?

javascript - 测试在切换方法之后是否有条件地渲染子组件

javascript - 使每条 Canvas 线都可拖放

javascript - 将键盘和鼠标事件发送到 Flash Movie

javascript - 在 Bootstrap Accordion 标题中有一个可点击的元素