While working with a custom directive in AngularJS, I encountered an issue. I wanted to scroll the window to the data-target
element upon clicking it, but unfortunately, I kept getting an error saying el.bind is not a function
.
The code for the custom directive looks like this:
'use strict';
app.directive("productfinderpage", ["$window","$document", function($window, $document) {
console.log("enter into directive");
return {
restrict: "AC",
link: function () {
// get all anchors
var anchors = angular.element(document.querySelectorAll("a[data-target]"));
angular.forEach(anchors, function (el) {
el.bind("click", function (e) {
var targetLink = e.target.dataset.target;
var targetContext = angular.element(document.querySelector("[data-name=\"" + targetLink + "\""));
var targetContextInt = targetContext.offsetTop;
// initiate scroll
scrollTo(scrollable, targetContextInt, 225);
});
});
// scroll to function
function scrollTo(element, to, duration) {
if (duration <= 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
setTimeout(function () {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop == to) return;
scrollTo(element, to, duration - 10);
}, 10);
}
}
};
}]);
The corresponding HTML code is as follows:
<div productFinderPage class="modal-body">
<div class="info" data-sticky="data-sticky">
<div class="info-inner">
<div class="lender-image">LOGO</div>
<div class="package-name"></div>
<div class="cta">
<button class="primary">Add to Favorites</button>
</div>
<nav>
<ul class="info-section">
<li><a href="#" data-target="basicInfo">Basic Information</a></li>
<li><a href="#" data-target="extInfo">Extended Information</a></li>
<li><a href="#" data-target="loanSize">Loan Size / LVR</a></li>
<li><a href="#" data-target="loanFees">Loan Fees</a></li>
<li><a href="#" data-target="services">Services</a></li>
</ul>
</nav>
</div>
</div>
<div class="main-details">
<div class="panel" data-name="basicInfo">
<div class="panel-header">Basic Information</div>
</div>
<div class="panel" data-name="extInfo">
<div class="panel-header">Extended Information</div>
</div>
<div class="panel" data-name="loanSize">
<div class="panel-header">Loan Size</div>
</div>
<div class="panel" data-name="loanFees">
<div class="panel-header">Loan Fees</div>
</div>
<div class="panel" data-name="services">
<div class="panel-header">Services</div>
</div>
</div>
</div>
You can check out the functioning of this code on jsfiddle.