Reputation: 2486
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.
Upvotes: 6
Views: 9066
Reputation: 411
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
Upvotes: 12