[英]Watch for screen size change in a directive Angularjs
I am having an issue with using $watch
in a directive. 我在指令中使用
$watch
遇到问题。 I want to update an elements left
and top
based on some basic information on the page. 我想更新的元素
left
和top
基于网页上的一些基本信息。 Below is my code: 下面是我的代码:
var myApp = angular.module("myApp", []); var offset_x_function = function(){ return (($('.map').width() / 2) - ($('#map_display_img').width() / 2)); } var offset_y_function = function(){ return (($('.map').height() / 2) - ($('#map_display_img').height() / 2)); } myApp.directive("plotDevice", function($window){ offset_x = offset_x_function(); offset_y = offset_y_function(); return { restrict: 'A', link: function(scope, elem, attrs){ scope.$watch(function(){ return $window.innerWidth; }, function(value) { offset_y = offset_y_function(); offset_x = offset_x_function(); }); scope.$watch(function(){ return $window.innerHeight; }, function(value) { offset_y = offset_y_function(); offset_x = offset_x_function(); }); angular.element(elem).css("left", (parseInt(offset_x) + parseInt(attrs["x"])).toString() + "px" ); angular.element(elem).css("top", (parseInt(offset_y) + parseInt(attrs["y"])).toString() + "px" ); } } });
.map { height: calc(100vh - 73px); width: 100%; } .map img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div class="map"> <img id="map_display_img" src="some/image/path" width="1000" height="1000" /> <div plot-device data-x="100" data-y="200"><p>item over image</p></div> </div>
While the directive works when the page loads: All plot-device
elements get a style with a left
and top
. 当指令在页面加载时起作用时:所有
plot-device
元素的样式都为left
和top
。 When the screen size is adjusted the style is not updated. 调整屏幕大小后,样式不会更新。
You are only setting offset_x
and offset_y
in the $watch
callback. 您仅在
$watch
回调中设置 offset_x
和offset_y
。 You are never actually updating the element except when the directive initializes. 除了指令初始化时,您实际上从未更新过该元素。
You would need the angular.element(elem).css("left", ...)
and angular.element(elem).css("top", ...)
lines in the $watch
callback. 您需要在
$watch
回调中使用angular.element(elem).css("left", ...)
和angular.element(elem).css("top", ...)
行。 (Ideally you would have them in a function that gets called at initialization and in the $watch
callbacks) (理想情况下,您会将它们放在在初始化和
$watch
回调中调用的函数中)
On a side note, there is a $window.on('resize', function(event){})
event you could listen for instead of using watchers. 附带说明一下,您可以侦听
$window.on('resize', function(event){})
事件,而不必使用观察程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.