I would like to synchronize the width of DOM elements such that the width is always the smallest width that can accommodate the content. I can successfully increase the size by $watching for an increase (based on ref1 & ref2), but I can't figure out how to shrink the element after it's been enlarged.
Angular directive:
app.directive('syncWidth', function () { //declaration; identifier master
return {
restrict: 'A',
link: function (scope, element) {
var linkElement = element[0];
scope.$watch(
function () {
return (linkElement.scrollWidth);
},
function (newValue, oldValue) {
if (newValue > oldValue) {
scope.testWidth = {
'min-width': newValue + 'px'
}
}
},
true
);
}
};
});
HTML:
<input type="text" ng-model="myText">
<input type="text" ng-model="myText2">
<div sync-width="test" style="background-color: lightblue" ng-style="testWidth">1 [{{myText}}]</div>
<div sync-width="test" style="background-color: lightcoral" ng-style="testWidth">2 [{{myText2}}]</div>
I'm assuming the issue is that the two elements are referencing another. I'm thinking the pseudocode would look something like:
Set a global groupMinWidth variable
Detect element.contentWidth changed
If newContentWidth > groupMinWidth {
groupMinWidth = newContentWidth;
}
If oldContentWidth == groupMinWidth {
check all synchronized elements and set groupMinWidth to the largest contentWidth;
}
Thanks for the help.