6

I want a directive to watch the result of an attribute expression such as:

<div scroll-if="test === selectedTest"></div>

So that it can then react to the change and scroll to the particular element. I seem to be struggling to find out how I can watch for changes to that expression.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Ben_hawk
  • 2,476
  • 7
  • 34
  • 59
  • possible duplicate of [How to get evaluated attributes inside a custom directive](http://stackoverflow.com/questions/12371159/how-to-get-evaluated-attributes-inside-a-custom-directive) – David says Reinstate Monica Mar 28 '15 at 01:36

1 Answers1

12

Use $watch:

app.directive('scrollIf', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attributes) {

      var actionScroll = function(newVal, oldVal) {
        if(newVal!==oldVal) {
          console.log("scrolling");
        }
      }

      scope.$watch(attributes.scrollIf, actionScroll);
    }
  }
});

$watch can evaluate the attribute expression scroll-if, the actionScroll listener will run if this expression is true.

Is necessary to add the condition newVal!==oldVal, because actionScroll always runs the first time. This is explained in the $watch documentation

psycho brm
  • 7,494
  • 1
  • 43
  • 42
Carlos Forero
  • 401
  • 1
  • 5
  • 10