之前在 Stack Overflow 上曾有人问过这个问题,但由于某种原因,我不断收到某些属性未定义的错误!
所以我有以下 Controller :
phonecatControllers.controller('AboutCtrl', function($scope, $state) {
$scope.startListenToScroll = function($scope, $state) {
$('.subsection').each(function(i) {
var position = $(this).position();
$(this).scrollspy({
min: position.top,
max: position.top + $(this).height(),
onEnter: function(element, position) {
if (element.id) {
$state.transitionTo('about.' + element.id);
} else {
$state.transitionTo('about');
}
}
});
});
}
$scope.startListenToScroll($scope, $state);
$scope.stopListenToScroll = function() {
$('.subsection').unbind().removeData();
}
});
它有两个函数,用于将滚动 spy 插件绑定(bind)和取消绑定(bind)到我的“关于”页面中的某个区域。
我还有一个指令,可以在单击链接时将用户滚动到某些部分:
.directive('scrollTo', function() {
return {
link: function(scope, element, attrs) {
element.bind('click', function() {
scope.stopListenToScroll();
var divPosition = $('#' + attrs.scrollTo).offset();
$('html, body').animate({
scrollTop: divPosition.top
}, "slow", function() {
scope.startListenToScroll();
});
});
}
};
});
正如你所看到的,我在单击时调用了scrollspy的取消绑定(bind),然后在动画完成后重新绑定(bind)它们。这是停止scrollspy插件监听scrollTo动画引起的滚动。
但是我收到错误:Uncaught TypeError: Cannot read property 'transitionTo' of undefined
大概是因为它看不到 $state。
您会注意到我没有在指令中传递任何内容,但这是因为它应该在 Controller 中默认,对吧?如果没有,我该如何处理?
有什么想法吗?
最佳答案
首先,我强烈建议您不要将 dom 事件逻辑放入 Controller 中,这违背了 Angular 团队为防止这种情况发生而所做的一切。
在你的情况下我会做的是创建一个类似这样的指令:
.directive('scrollAnchor', function($state) {
return {
link: function(scope, element, attrs){
scope.startListenToScroll = function(){
var position = element.position();
element.scrollspy({
min: position.top,
max: position.top + $(this).height(),
onEnter: function(ele, position) {
if(ele.id){
$state.transitionTo('about.'+ele.id);
} else {
$state.transitionTo('about');
}
}
});
};
scope.stopListenToScroll = function(){
element.off().removeData();
};
},
controller: function($scope){
this.startListenToScroll = $scope.startListenToScroll;
this.stopListenToScroll = $scope.stopListenToScroll;
}
};
});
并且根据您当前使用scrollTo指令的位置,您可以使其需要scrollAnchor,从而能够在其 Controller 中调用使用“this”关键字定义的函数,例如
.directive('scrollTo', function() {
return {
require: 'scrollAnchor',
link: function(scope, element, attrs, scrollAnchorCtrl) {
element.bind('click', function() {
scrollAnchorCtrl.stopListenToScroll();
var divPosition = $('#'+attrs.scrollTo).offset();
$('html, body').animate({
scrollTop: divPosition.top
}, "slow", function(){
scrollAnchorCtrl.startListenToScroll();
});
});
}
};
});
我还没有尝试过这段代码,只是将其作为概念证明,以便您可以检查它是否适合您的需求。
干杯!
如果此代码不能满足您的所有需求,那么我建议将一些逻辑移至服务并使其具有 dom 感知能力。这不是最佳实践,但在某些情况下它是可接受的解决方案。
刚刚为您准备的需要使用共享指令逻辑的示例! http://plnkr.co/edit/IxvLbGdNmkFfroCRX5sO?p=preview
干杯!
关于javascript - 在 AngularJS 指令中调用 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25625865/