still working my head around angularjs directives and am a bit confused why this isn't working.
namely, i want a directive that tracks its position relative to a target and sets a target hit boolean. i also want to reuse this directive on my page, with each directive tracking a unique target.
app.directive('trackPosition', [function() {
return {
restrict: 'A',
scope: {
target: "=target"
},
link: function(scope, elem, attrs) {
var navtop = elem[0].offsetTop;
window.onscroll = function() {
var elemTop = elem[0].offsetTop;
targetTop = document.getElementById(scope.target).getBoundingClientRect().top;
console.log(scope.title + ", " + elemTop + ", " + targetTop);
(targetTop <= elemTop && (-1 * targetTop) <= elemTop) ? scope.trackedTargetHit = true : scope.trackedTargetHit = false;
scope.$apply();
}
}
}
}]);
portfolio.controller('CtrlOne', function($scope) {
$scope.title = 'CtrlOne';
$scope.target = 'TargetOne';
$scope.trackedTargetHit = false;
});
portfolio.controller('CtrlTwo', function($scope) {
$scope.title = 'CtrlTwo';
$scope.target = 'TargetTwo';
$scope.trackedTargetHit = false;
});
<div ng-controller="CtrlOne" >
<section ng-class="{'white' : trackedTargetHit}" track-position target="target">
</section>
</div>
<div ng-controller="CtrlTwo" >
<section ng-class="{'white' : trackedTargetHit}" track-position target="target">
</section>
</div>
this works fine with just one directive, but used twice it musses up. i know this has something to do with my misuse of scopes in the directive. but getting very confused about how to use correctly; any suggestions greatly appreciated. thanks.