[英]AngularJS directive watch parent size change
我有一個簡單的指令,執行特定元素的大小更新。 這會監視窗口大小並相應地進行調整。
MyApp.directive('resizeTest', ['$window', function($window) {
return {
restrict: 'AC',
link: function(scope, element) {
var w = angular.element($window);
scope.$watch(function() {
return { 'h': w.height(), 'w': w.width() };
}, function(newValue, oldValue) {
// resizing happens here
}, true);
w.bind('resize', function() { scope.$apply(); });
}
};
}]);
這很好用。
它恰好發生在與之關聯的div
標簽內部,我有一個子div
。 調整父級的大小時,我想對子元素進行定位更改。 但是,我無法觸發。
這會在啟動時調用,但在調整元素大小或窗口更改時不會觸發:
MyApp.directive('centerVertical', ['$window', function($window) {
return {
restrict: 'AC',
link: function(scope, element) {
element.css({border: '1px solid #0000FF'});
scope.$watch('data.overlaytype', function() {
$window.setTimeout(function() {
console.log('I am: ' + element.width() + 'x' + element.height());
console.log('Parent is: ' + element.parent().width() + 'x' + element.parent().height());
}, 1);
});
}
};
}]);
我應該使用什么類型的綁定或監視配置來檢查父元素的大小調整?
您在centerVertical
指令中觀察到的值data.overlaytype
不在scope
上,因此結果值是undefined
並且此值永遠不會改變,這就是您不執行偵聽器的原因。 要檢查父元素的大小是否已更改,您可以在$ watch函數中檢查它,如下所示:
scope.$watch(
function () {
return {
width: element.parent().width(),
height: element.parent().height(),
}
},
function () {}, //listener
true //deep watch
);
此外,請記住,當你想使用一個已經存在的模塊時,你不能像這個angular.module('myModule', [])
那樣調用它angular.module('myModule', [])
因為這意味着創建新模塊。 你必須傳遞模塊名稱angular.module('myModule')
,這是你的代碼無法工作的第二個原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.