仍然我的頭繞着angularjs指令,我有點困惑,爲什麼這不起作用。瞭解angularjs指令和數據綁定
即,我想要一個指令,跟蹤它相對於目標的位置並設置目標點擊布爾值。我也想在我的頁面上重複使用這個指令,每個指令跟蹤一個唯一的目標。
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>
這工作正常,只有一個指令,但使用兩次它發起。我知道這與我在指令中濫用範圍有關。但對如何正確使用感到困惑;任何建議不勝感激。謝謝。
啊。說得通。謝謝。這對我現在有用。 – vesperae