[英]Watch for screen size change in a directive Angularjs
我在指令中使用$watch
遇到問題。 我想更新的元素left
和top
基於網頁上的一些基本信息。 下面是我的代碼:
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>
當指令在頁面加載時起作用時:所有plot-device
元素的樣式都為left
和top
。 調整屏幕大小后,樣式不會更新。
您僅在$watch
回調中設置 offset_x
和offset_y
。 除了指令初始化時,您實際上從未更新過該元素。
您需要在$watch
回調中使用angular.element(elem).css("left", ...)
和angular.element(elem).css("top", ...)
行。 (理想情況下,您會將它們放在在初始化和$watch
回調中調用的函數中)
附帶說明一下,您可以偵聽$window.on('resize', function(event){})
事件,而不必使用觀察程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.