$ watch指令中的元素宽度

nco*_*hen 12 javascript angularjs angularjs-directive

我正在尝试$watch在指令中使用元素的宽度:

appDrct.directive('setWidth', function($interval) {
    return {
        require: '?ngModel',
        link: function($scope, $elm, attr, ngModel) {

            $scope.$watch($elm.parent().width(), function() {
                console.log('Width changed');
            });
        }
     }
})
Run Code Online (Sandbox Code Playgroud)

但它不起作用......我知道我的宽度发生了变化(我尝试$interval显示宽度并改变)

Omr*_*ron 8

这是你如何做到的,你需要$watch函数表达式:

$scope.$watch(function () {
        return $element[0].style.width;
       }, function(newVal, oldVal) {
        console.log('Width changed');
});
Run Code Online (Sandbox Code Playgroud)

小提琴