AngularJS在指令内部监视窗口调整大小。
AngularJS在指令内部监视窗口调整大小。
我有一个类似于下面这样的揭示模块模式:
'use strict'; angular.module('app', []) .directive('myDirective', ['SomeDep', function (SomeDep) { var linker = function (scope, element, attr) { // 一些操作 }; return { link: linker, restrict: 'E' }; }]) ;
我遇到的问题是如何将$watch集成到其中。具体来说,我希望使用'$window'服务来监视窗口大小的调整。
[编辑]:
我意识到我一直以来的问题是...我将它限制为元素,但我忘记了我将其实现为属性...
@_@;
这个问题的出现的原因是问题提问者错误地将问题标记为AngularJS,但实际上给出的代码是Angular 2.0的代码。因此,解决方法是将代码修改为AngularJS的代码。
以下是解决方法的代码:
---- AngularJS window resize directive. angular.module('myApp').directive('resize', function($window) { return { link: function(scope, element) { // Adjust height of element. function onResize() { element.css('height', ($window.innerHeight - 163) + 'px'); } // Window resize listener angular.element($window).bind('resize', function() { onResize(); }); // Initial resize call onResize(); } }; });
完成以上修改后,问题就得到了解决。
问题的出现的原因是:当directive不再在页面上使用时,仍然会触发resize事件,导致事件处理程序被多次调用。
解决方法是:在directive上实现$destroy方法来清除事件绑定。
以下是修复后的代码:
'use strict'; var app = angular.module('plunker', []); app.directive('myDirective', ['$window', function ($window) { return { link: link, restrict: 'E', template: 'window size: {{width}}px', scope: {}, controller: function($scope){ $scope.onResize = function(){ $scope.width = $window.innerWidth; $scope.$digest(); } }, link: function(scope, element, attrs){ angular.element($window).on('resize', scope.onResize); scope.$on('$destroy', function(){ angular.element($window).off('resize', scope.onResize); }); } }; }]);
对于不再使用的directive,通过实现$destroy方法来清除事件绑定。
参考链接:[how to safely clean up angularjs event binding in a directive](http://stackoverflow.com/questions/23031381)
AngularJS的$watch函数用于监听变量的变化,并在变化时执行相应的操作。在本例中,$watch函数用于监听$scope中的width变量的变化。
问题出现的原因是,在directive中监听了窗口的resize事件,并在事件发生时更新$scope中的width变量。然而,在离开当前视图时,没有解绑resize事件监听器,导致在切换视图后仍然会触发事件回调函数,从而可能引发一些问题。
为了解决这个问题,需要在directive的link函数中添加一个清理函数cleanUp,用于解绑resize事件监听器。在$scope销毁时,通过调用cleanUp函数来解绑事件监听器,从而避免产生"zombie listeners"。
修正后的代码如下所示:
(function() { 'use strict'; angular .module('myApp.directives') .directive('resize', ['$window', function ($window) { return { link: link, restrict: 'A' }; function link(scope, element, attrs){ scope.width = $window.innerWidth; function onResize(){ { scope.width = $window.innerWidth; scope.$digest(); } }; function cleanUp() { angular.element($window).off('resize', onResize); } angular.element($window).on('resize', onResize); scope.$on('$destroy', cleanUp); } }]); })();
修正后的代码中,在$scope销毁时会调用cleanUp函数来解绑resize事件监听器,从而避免产生"zombie listeners"问题。
在HTML中使用resize指令的代码如下所示:
此外,控制器中也可以使用$watch函数来监听$scope中width变量的变化,并在变化时执行相应的操作。例如:
$scope.$watch('width', function(old, newv){ console.log(old, newv); });
通过以上的修正和使用,可以解决在directive中监听窗口resize事件时可能产生的问题,并确保在离开当前视图时正确解绑事件监听器,避免产生"zombie listeners"。