0

I am trying to watch the width of a directive's element (the directive itself). In the demo below I set the element style to 100%, in the real world app the element resizes through media queries.

Here is my approach: http://jsfiddle.net/fusio/5zgaj79b/

scope.$watch(
  function() { 
    return element.width()
  }, 
  function(val) { 
    console.log(val) 
  }, 
  true
);

Is .width() not changing?

1

1 Answer 1

1

The reason it is not triggering is that, for the first function to get called, a digest cycle has to be triggered. How to do it? Try adding the following to your fiddle:

angular.module('HelloApp', ['components']).run(function($rootScope) {
    $(window).on("resize", function() {
        $rootScope.$apply();
    });
});

For a real scenario, you may want to limit the scope of the $apply to a specific scope, so as not to cause unnecessary watcher invocations.

Sign up to request clarification or add additional context in comments.

4 Comments

But then I can avoid using the watcher altogether.. right? jsfiddle.net/fusio/5zgaj79b/1 What if more than 1 directive has to watch for its width, though? Should I go on adding .on events?
(1) The watcher does the important job of watching something and reacting to a change. My snippet above simply makes certain that an event external to Angular will trigger a digest cycle. (2) If more than one watchers need to watch for element size changes you go on and add watches. The run() function remains untouched. (3) The code in the second fiddle just prints something to the console. If you wanted to interact with Angular, you would need to trigger the digest calling $apply().
Ok, so ideally I should call window.on only once, in the application .run, right? (otherwise I would have multiple unnecessary observers on window) If this is the case, then how can I use the directive scope instead of rootScope? Thank you :)
In this case you will have to use the $rootScope. Or refactor the logic to use events, if performance really suffers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.