指示中的角度手表元素高度

Angular watch element height in directive

本文关键字:手表 元素 高度 指示      更新时间:2023-09-26

我正在尝试这样做:

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来监控高度变化并进行更新。我的代码确实有效,但问题是它不能立即更新。

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

使用$scope.apply()

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

它可能有助于你…