我有一个Angular指令,它将元素的高度设置为等于浏览器窗口的内部高度(+/-给定的偏移量).该指令响应窗口的"resize"事件并相应地调整其高度.当我的指令范围发出'$ destory'事件时,我删除了对"resize"事件的绑定(我认为保留它会导致一些问题,如果我错了就纠正我).
我不知道如何以"安全"的方式做这个事件分离.如果我在我的应用程序中有多个此指令实例,如果我有其他指令附加到'resize'事件怎么办?
JQuery具有事件命名空间的概念,这似乎是一个很好的解决方案,但Angular的实现(JQLite)不支持这一点.因为我已经在使用Angular,所以我宁愿不使用JQuery,所以我该怎么办?
这是我今天指令的代码
window.angular.module('arcFillClient', [])
.directive('arcFillClientY', ['$window',
function ($window) {
function link($scope, el, attrs) {
var setHeight,
onResize,
cleanUp;
setHeight = function (offSetY) {
var newHeight;
offSetY = offSetY || 0;
newHeight = Math.max($window.innerHeight + parseInt(offSetY, 10)) + 'px';
el.height(newHeight);
};
onResize = function () {
var offset;
offset = attrs.arcFillClientY || 0;
setHeight(offset);
};
attrs.$observe('arcFillClientY', setHeight);
window.angular.element($window).on('resize', onResize);
cleanUp = function () {
window.angular.element($window).off('resize');
};
$scope.$on('$destroy', cleanUp);
}
return {
link: link
};
Run Code Online (Sandbox Code Playgroud)
更新看起来像RTFM的情况,但万一其他人徘徊在这里,这里有一些更多的信息.将原始函数(在我的情况下 …
我可以通过控制器调整大小来获得angularJS中的窗口宽度吗?我希望能够得到它,所以我可以显示一些div与<div ng-if="windowWidth > 320">
我可以在初始页面加载时获取windowWidth,但不能在调整大小时...
'use strict';
var app = angular.module('app', []);
app.controller('mainController', ['$window', '$scope', function($window, $scope){
var mainCtrl = this;
mainCtrl.test = 'testing mainController';
// Method suggested in @Baconbeastnz's answer
$(window).resize(function() {
$scope.$apply(function() {
$scope.windowWidth = $( window ).width();
});
});
/* this produces the following error
/* Uncaught TypeError: mainCtrl.$digest is not a function(…)
angular.element($window).bind('resize', function(){
mainCtrl.windowWidth = $window.innerWidth;
// manuall $digest required as resize event
// is outside of angular
mainCtrl.$digest();
});
*/
}]); …Run Code Online (Sandbox Code Playgroud)在非角度应用程序中,我们可以通过以下方式响应窗口大小调整事件:
window.onresize = function(event) {
console.log('changed');
};
Run Code Online (Sandbox Code Playgroud)
但是,我们不能在角度应用程序中使用它,因为直接访问窗口对象是一种不好的做法。我们如何以“角度”方式实现上述功能?