【问题标题】:Angular watch element height in directive指令中的角度观察元素高度
【发布时间】:2015-03-16 22:17:37
【问题描述】:

我正在尝试做这样的事情:

index.html

<div ng-controller="MyController" menu>
    <input ng-model="myVar"/>
    <div slimscroll="{'height':menuheight,'alwaysVisible':true}">
        <div id="menucontent" menu-content>
        </div>
    </div>
</div>

当输入字段中有文本时,它将对menu-content指令进行过滤。当它过滤时,menu-content 的高度会发生变化。

菜单指令:

angular.directive('menu', function(){
    return function (scope, element) {
        var menuContentHeight = $("#menucontent").height();
        scope.menuContentHeight = function(){
            return $("#menucontent").height();
        };

        scope.$watch(scope.menuContentHeight, function(newValue, oldValue) {
            if (newValue !== oldValue) {
                console.log('Changed!');
                menuContentHeight = newValue;
                adjustHeight();
            }
        },true);

        function adjustHeight(){
            // Perform height adjustment
        }
    };
});

所以,我想做的是使用scope.watch 来监控高度变化并进行更新。我的代码确实有效,但问题是它不会立即更新。

如何在高度改变后立即获得高度调整更新?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    使用 $scope.apply()

    scope.$watch(scope.menuContentHeight, function(newValue, oldValue) {
                if (newValue !== oldValue) {
                    console.log('Changed!');
                    menuContentHeight = newValue;
                    adjustHeight();
                    $scope.apply();  //call digest cycle
                }
            },true);
    

    它可能对你有帮助......

    【讨论】:

    • 试过了。问题不在于调用摘要周期。我猜是 scope.$watch 的事情,因为一旦它更新视图,它就会控制台注销消息。]
    猜你喜欢
    • 2019-01-15
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多