K
K
kult2014-10-07 18:58:25
Angular
kult, 2014-10-07 18:58:25

Angular.js how to track element height change in directive?

there is a directive:
myModule.directive("positioning", function($http, $compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
return scope.$watch((function() {
return $(element).height();
}), function(newValue, oldValue) {
return console.log(newValue);
});
}
};
});
but it works twice, as I understood right away when the values ​​\u200b\u200bare not substituted and after they were substituted.
Is it possible to trace only the second option?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2014-10-07
@iNikNik

Maybe this method will help you

myModule.directive("positioning", function($http, $compile) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var height;
            $(element).load(function(){
                height = $(this).height();
            });
            return scope.$watch((function() {
                return height;
            }), function(newValue, oldValue) {
                return console.log(newValue);
            });
        }
    };
});

M
maxaon, 2014-10-16
@maxaon

the processing function is always called once before working with identical parameters. If you need to perform actions only on change, add a comparison. There's also no need to wrap the element again in jQuery, it's already wrapped (if you've included jQuery correctly - before angular). Also keep watchExp as fast as possible since it is called many times per digest cycle. If you can do without working from home, do it.
As a result, the directive might look like this:

myModule.directive("positioning", function ($http, $compile) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var rawElement=element[0];
      return scope.$watch((function () {
        return rawElement.clientHeight;
      }), function (newValue, oldValue) {
        if (newValue === oldValue)
          return;
        return console.log(newValue);
      });
    }
  };
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question