在我的应用程序中,我使用了一个自定义指令和一个窗口调整大小的事件侦听器:
link: function(scope, elem, attrs) {
angular.element($window).bind('resize', function() {
// viewId is a unique reference to the view in which the directive lives
console.log(scope.viewId);
});
}
此指令在我的每个视图中插入1次或多次。
令我困惑的是,为什么函数不仅对活动视图执行,而且对非活动视图执行。一旦我访问了多个视图,就会发生这种情况。
更让我困惑的是,为什么在我多次访问同一个视图之后,这个函数被从同一个视图多次调用。
在我看来,旧的指令作用域没有被破坏,而是保持了活力,并且在旧的指令范围的基础上创建了一个新的作用域。
我能做些什么来阻止这种行为吗?
下面是基于提供的答案的工作解决方案的代码片段(我正在使用LoDash _.debounce来防止函数被频繁调用):
windowResize = _.debounce(function () {
// My logic
$scope.$apply();
}, 150);
// Attach debounced function to the window.resize event listener
angular.element($window).on('resize', windowResize);
// Remove the function when the directive is destroyed
$scope.$on('$destroy', function () {
angular.element($window).off('resize', windowResize);
});
发布于 2015-12-15 11:49:11
当您的指令被销毁时,您需要删除侦听器。类似于:
angular.element($window).on('resize', resize);
scope.$on('$destroy', function () {
angular.element($window).off('resize', resize);
});
function resize(){
...
}
发布于 2015-12-15 11:55:08
在指令中,对于每个具有相同名称角的指令,只调用一次链接函数。
因此,如果视图中有两次指令,它将执行两次链接函数。
如果您只想运行函数一次,只需在“编译”函数中执行您的操作即可。
查看本教程,他很棒:http://www.sitepoint.com/practical-guide-angularjs-directives/
https://stackoverflow.com/questions/34288157
复制相似问题