Angular: Empty Fiddle
http://angularjs.org/
by Bretto
HTML
<script src="http://code.angularjs.org/angular-1.0.0rc8.js"></script>
<div ng-controller="MyCtrl">
Position of box {{debug}}
<button ng-click="update()">update</button>
<button ng-click="nothing()">nothing</button>
<br>
<span class="light">Position should update automatically when change the position of element...</span>
<div id="ud" class="floater" updater="update()"></div>
</div>
CSS
.floater {
position: absolute;
top: 30%;
left: 30%;
width: 30%;
height: 30%;
background-color: whitesmoke;
border: thin solid lightgray;
}
.light { color: grey}
JavaScript
function position( elem ) {
var left = 0,
top = 0;
do {
left += elem.offsetLeft;
top += elem.offsetTop;
} while ( elem = elem.offsetParent );
return [ left, top ];
};
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.directive("updater", function(){
return {
restrict: "AC",
scope: {
updater: 'expression'
},
link: function(scope, element, attr) {
var lastPosition = position(element[0]);
scope.$watch(function() {
var np = position(element[0]);
if (!angular.equals(np, lastPosition)) {
return np;
} else {
return lastPosition;
}
}, function(newValue) {
lastPosition = newValue;
scope.updater();
});
}
};
});
function MyCtrl($scope) {
$scope.$watch(
function(){ return position(document.getElementById('ud')); },
function(val) { $scope.debug = val; },
true
);
$scope.update = function() {
$scope.debug = position(document.getElementById('ud'));
};
$scope.nothing = function(){
//only to call digest
};
}