2016-08-11 39 views
0

我在指令中使用$watch时遇到问题。我想根据页面上的一些基本信息更新元素lefttop。下面是我的代码:观察指令中屏幕大小的变化Angularjs

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元素得到一个lefttop风格。当调整屏幕尺寸时,样式不会更新。

回答

1

你只是$watch回调设置offset_xoffset_y。除非指令初始化,否则绝不会实际更新元素。

您需要在$watch回调中的angular.element(elem).css("left", ...)angular.element(elem).css("top", ...)行。 (理想情况下,你可以让它们在初始化和$watch回调中调用的函数)

在附注中,有一个$window.on('resize', function(event){})事件可以监听,而不是使用监视器。