Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS/jQuery: changing text in span doesn't fire resize event

I'm having trouble getting jQuery's resize event to fire on a span, after I've changed the text inside the span.

I'm applying the event handlers to the span element using an AngularJS directive:

angular.module("test.directives", [])
    .directive("trackSize", ["$parse", function($parse) {
        return function(scope, element, attrs) {
            function callback() {
                var size = { w: element.width(), h: element.height() };
                scope[attrs.trackSize].call(scope, size);
            }
            element.on("resize", function() {
                console.log("resize");
                scope.$apply(callback);
            });
            callback();
        };
    }]);

but I'm not seeing the callback fire when the text inside the span changes. If it's relevant: the text is being changed using an embedded AngularJS expression.

My actual (full) code snippet can be seen on the jsFiddle at: http://jsfiddle.net/KkctU/13/

like image 625
sheu Avatar asked Oct 21 '22 18:10

sheu


1 Answers

The resize event isn't meant for elements inside the document like a span. It's made for use on the window only.

Here is a plugin that might help you. I've not used it, but it seems like it's along the right track for you.

In the end, though, it might be better/easier to just set up a watch in your directive on whatever is bound to it, then check to see if the height and width have changed when the text changes. Just as an idea:

app.directive('trackSize', function () {
   return function(scope, element, attrs) {
       var w = element.width(),
           h = element.height();
       scope.$watch(attrs.trackSize, function(v) {
           element.text(v);
           var w2 = element.width(),
               h2 = element.height();
           if(w != w2 || h != h2) {
              //TODO: do something here, the size has changed.
           }           
       });
   }
});
like image 136
Ben Lesh Avatar answered Oct 29 '22 19:10

Ben Lesh