我有一个动态Web应用程序,可以在按钮单击时更改页面视图。我有一个页面是一个滚动页面,"间谍"在这些部分,类似于Bootstrap的滚动间谍。当只有一页时,它按预期工作。
如果有多个页面,则每次导航到其中一个滚动页面时都会添加该元素,但仅在滚动功能中添加。 (即第1页:element = element,第2页:element = element * 2,第3页:element = element * 3,依此类推)。这打破了滚动函数中的逻辑并产生TypeError: $(previous).offset().top
未定义。
以下是观点:
<div id="scroll-container" class="row" scroll-spy>
<div class="container sidebar grid_4">
<div class="well">
<nav class="page-nav">
<ul class="">
<li class="spy" ng-repeat="group in currentPage.Group" data-spy="{{group.id}}" >
<a href="javascript:void(0)" role="link" ng-bind-html="group.Title.html" ng-click="scrollTo(group.id)"><span class="right-arrow"></span></a>
</li>
</ul>
</nav>
</div>
</div>
<div class="container content grid_12">
<h2 ng-bind-html="currentPage.Title.html"></h2>
<div class="group row" ng-repeat="group in currentPage.Group" id="{{group.id}}">
<h3 ng-bind-html="group.Title.html"></h3>
<p class="lead" ng-repeat="item in group.SimpleText" ng-bind-html="item.html"></p>
<hr class="group-divider"/>
</div>
</div>
这是指令:
define(['../../../directives/application/MainDirective'], function(directives){
directives.directive('scrollSpy',['$rootScope','$state','$stateParams','$location','$anchorScroll','$window','$compile',function($rootScope,$state,$stateParams,$location,$anchorScroll,$window,$compile){
return{
restrict: 'A',
controller: function($scope){
$scope.spies = [];
},
terminal: false,
link: function($scope,pElement,attrs){
var api = $scope.$parent;
var trace = api.trace;
var elem = pElement;
var sidebar = pElement.find(".sidebar");
var offset = sidebar.offset();
var topPadding = 50;
var links = [];
var listener = $scope.$watch('spies',function(spies){
elem.find("li.spy").eq(0).addClass("active");
links = elem.find("li.spy").click(function(event){
var spy = $(this);
$(this).toggleClass("active");
$location.hash(spy.attr("data-spy"));
$anchorScroll();
});
});
angular.element($window).bind("scroll", function(e){
var current = {}, spy = {}, previous = {};
links.each(function(index){
previous = index > 0 ? $("#"+links.eq(index - 1).attr("data-spy")) : null;
if(!previous) current = $(this);
else if($(previous).offset().top + $(previous).outerHeight() < window.scrollY) current = $(this);
});
links.removeClass("active");
current.addClass("active");
if($($window).scrollTop() > offset.top) {
sidebar.stop().animate({
marginTop: $($window).scrollTop() - offset.top + topPadding
});
} else {
sidebar.stop().animate({
marginTop: 0
});
}
});
$scope.$on('$destroy',function(){
trace("destroying");
});
}
};
}]);
});
我知道$window
&#39;存在&#39;在棱角分明之外,我试过$apply()
,但也许我没有正确使用它?这个滚动功能是否需要它自己的服务?任何帮助表示赞赏。