【发布时间】:2014-02-20 18:16:33
【问题描述】:
我是 AngularJS 的新手,已经处于绝望的边缘 :) 我的应用看起来像这样 (Not-working example on Plnkr):
HTML
<div ng-app="myApp" ng-controller='controllers.content' >
<h2 id="fixed">{{ header }}</h2>
<ul>
<li ng-repeat="item in db" scroll-stop="item">{{ item.name }}</li>
</ul>
</div>
JS
angular.module('myApp.controllers',[]);
var app = angular.module('myApp', [
'myApp.controllers'
]);
var app = angular.module('myApp.controllers').controller('controllers.content', ['$scope', function($scope){
$scope.db = [
{ name: "20 February 2014", header: "Today" },
// ...
];
$scope.header = "Today";
}]);
现在基本上我想要一个滚动间谍,只要该项目当前位于顶部视口:
app.directive('scrollStop', function() {
return {
restrict: 'A',
scope: {
scrollStop:'='
},
link: function (scope, element, attrs) {
var $page = angular.element(window)
var $el = element[0]
var last_top = $el.getBoundingClientRect().top - 60;
$page.bind('scroll', function () {
var current_top = $el.getBoundingClientRect().top - 60;
if (last_top >= 0 && current_top < 0) {
// HERE!
console.log(scope.scrollStop.header);
scope.header = scope.scrollStop.header;
}
last_top = current_top;
})
}
}
});
但是,我不知道如何从指令中与content 控制器对话,以从指令中编辑 $scope.header。我知道scope 与控制器的$scope 不同,并且有一种模糊的感觉,我应该在某个地方使用require,但无法弄清楚如何正确使用它。部分还因为在 AngularJS 中做任何事情似乎有 5 种不同的速记,而且它们并不总是能很好地结合在一起。任何帮助表示赞赏,包括风格指导。
【问题讨论】:
标签: javascript angularjs angularjs-directive scrollspy