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.
If expression is undefined, still fires directive link function, even though the directive is not added in the DOM. #16441.
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.
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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With