I have a directive that uses the computed style of its parent element to calculate its own width.
The first time a view is loaded that contains the directive, I get the correct computed style for the parent element. But after that, whenever I load the same view again, I get the wrong style.
I figure this must be something to do with caching within ionic, but I get the same issue when I turn caching off for the view AND when I turn caching off globally. Any ideas what I am missing?
This is the gist of what i am doing:
angular.module('app.directive')
.directive('myDirective', function ($window) {
var link = function (scope, element, attrs) {
var elementStyleMap = $window.getComputedStyle(element.parent()[0], null);
var paddingTop = elementStyleMap.getPropertyValue("padding-top").replace("px", "");
// first time this is called, padding top is 10px, which is correct
// all subsequent times the view is loaded and this is called, padding top is 1px
};
return {
restrict: 'E',
replace: true,
templateUrl: 'path/to/template.html',
link: link
};
});
I have solved this by using $timeout
to execute any code the tries to access the calculated styles after the DOM has finished loading.
My code now looks something like this:
angular.module('app.directive')
.directive('mydirective', function ($window, $timeout) {
var link = function (scope, element, attrs) {
$timeout(function () {
var elementStyleMap = $window.getComputedStyle(element.parent()[0], null);
var paddingTop = elementStyleMap.getPropertyValue("padding-top").replace("px", "");
});
};
return {
restrict: 'E',
replace: true,
templateUrl: 'path/to/directive.html',
link: link
};
});
This feels more like a workaround than a solution, but I am able to continue working.