AngularJS $watch for element width change
Asked Answered
S

1

6

I've been scouring the internet for the past 3 days trying to work out how to get a directive to run when angular notices a change in the width of a div. I keep seeing the same examples of how I'm supposed to achieve this but, they don't work for me and I don't know why.

I'm back at square one. All I am trying to do is: update a css property of a div (that has a directive as an attribute), when the div's width changes.

I need to know how to get angular to check when the property has changed.

This is what I have so far:

.directive('stayPut', function () {
    var linker = function (scope, element, attrs) {

        scope.getElemWidth = function () {
            return element.width();
        };

        scope.$watch(scope.getElemWidth, 
            function (newWidth, oldWidth) {
                var deltaWidth = newWidth - oldWidth;

                console.log(deltaWidth);

                element.css('top', 
                    (parseInt(element.css('top')) + 
                    deltaWidth)                   +
                    'px');
        }, true);

        element.bind('resize', function () {
            scope.$apply();
        });
    };

    return {
        link: linker,
        restrict: 'A'
    }
});

I know the issue here is:

element.bind('resize', function () {
    scope.$apply();
});

I have a vague understanding of how it works, but I don't understand why it doesn't work here.

Spaniard answered 26/7, 2015 at 7:24 Comment(0)
U
-1

Try using this:

element.on('resize', function () {
    scope.$apply();
});
Udelle answered 22/6, 2017 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.