Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : directive watch attribute expression

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.

like image 902
Ben_hawk Avatar asked Mar 28 '15 01:03

Ben_hawk


People also ask

What is Ng ATTR?

If expression is undefined, still fires directive link function, even though the directive is not added in the DOM. #16441.

What are the directives in AngularJS?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

What is restrict in AngularJS directive?

Restrict. Angular allows us to set a property named restrict on the object we return on our directive definition. We can pass through a string with certain letters letting Angular know how our directive can be used. function MyDirective() { return { restrict: 'E', template: '<div>Hello world!

What is bindings in AngularJS?

Data binding in AngularJS is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well.


1 Answers

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

like image 135
Carlos Forero Avatar answered Oct 15 '22 22:10

Carlos Forero