Angularjs 观察指令中的表达式直到鼠标悬停才应用

Angularjs 观察指令中的表达式直到鼠标悬停才应用,angularjs,angularjs-directive,Angularjs,Angularjs Directive,如果div宽度调整,我有以下指令来调整div的高度。由于未知的原因,当通过更改窗口大小来调整div宽度时,什么也不会发生-但是如果您调整窗口大小,然后将鼠标悬停在div上,则高度会按其应该的方式进行调整。请问我做错了什么 使用控制台时,我注意到调整窗口不会导致$watch执行。它仅在窗口大小更改后鼠标悬停在div上时执行 app.directive('cardHeight', function () { return { link: function (scope, element, a

如果div宽度调整,我有以下指令来调整div的高度。由于未知的原因,当通过更改窗口大小来调整div宽度时,什么也不会发生-但是如果您调整窗口大小,然后将鼠标悬停在div上,则高度会按其应该的方式进行调整。请问我做错了什么

使用控制台时,我注意到调整窗口不会导致$watch执行。它仅在窗口大小更改后鼠标悬停在div上时执行

app.directive('cardHeight', function () {
return {
    link: function (scope, element, attrs) {
        console.log("cardHeight", scope.data);

        scope.getWidth = function () {

            return element[0].offsetWidth;
        };


        scope.$watch(scope.getWidth, function (newWidth, oldWidth) {
            console.log("newold", newWidth, oldWidth);
            if (newWidth != oldWidth) {
                var divHeight = "height: " + newWidth / scope.data.aspectRatio + "px";
                attrs.$set("style", divHeight);

            }
        });





    },
    scope: {
        data: "=datad"
    }
}
})

$watchexpression、[listener]、[objectEquality]

注册在watchExpression更改时执行的侦听器回调

watchExpression在每次调用$digest时都会被调用,并且应该 返回将被监视的值。因为$digest在运行时会重新运行 检测watchExpression每次可以执行多次的更改 $digest,并且应该是幂等的

但是,只有在作用域发生变化时才会调用$digest,或者在调用方法时才会调用$digest。如果鼠标悬停在元素上,也可能发生这种情况

我宁愿使用.onresize事件,如下所示:

link: function (scope, element, attrs) {

    element[0].onresize=function() {
        scope.width=element[0].clientWidth;
        scope.$apply();
    };

    scope.$watch('width', function (newWidth, oldWidth) {
        console.log("newold", newWidth, oldWidth);
        if (newWidth != oldWidth) {
            var divHeight = "height: " + newWidth / scope.data.aspectRatio + "px";
            attrs.$set("style", divHeight);

        }
    });
},

感谢您抽出时间回复。我似乎没有定义width、newWidth和oldWidth的值。另外,当我改变窗口宽度时,$watch似乎不会启动。不知道为什么?抱歉,我忘了,您需要添加一个作用域。$apply以便运行摘要循环