Reputation: 3109
I'd like to determine if the length text exceeds the width of its container but in order to do that, I need to know when the data has been bound to the DOM.
Is there an event in AngularJS that tells me the page has been bound, or is using setTimeout
the only way to sidestep that?
Upvotes: 0
Views: 90
Reputation: 16263
Well, that depends;
If the data is not changed after it is linked, it's simply a matter of using the postLink()
function within the directive. This function is tied to the link
property of the directive by default, so you can simply evaluate the data on the spot:
link: function(scope, element, attrs) {
// element and data are linked, let's mess around with the DOM!
}
If the data is going to change after the linking phase (after the DOM is compiled and a scope is bound to it), it's a bit more convoluted.
There's no way of knowing when the digest cycle has ended (or when the data has finished updating), as each evaluation may change the data being evaluated and trigger another cycle.
The best you can do in such cases is arbitrarily decide when the data has finished changing - you can $watch
for changes on the bounded data, and decide that e.g. if the text is not soft-equaling the former text value, perform an action in the DOM.
link: function(scope, element, attrs) {
scope.$watch('counter', function(newVal, oldVal, curScope) {
if (newVal != oldVal) {
// data is re-evaluated, let's mess around with the DOM!
}
});
}
See a Demo for dynamic data evaluation.
Note that we are talking about detecting when the data is bound to the DOM, and not about whether the element is attached to the DOM. It shouldn't matter in most cases, but it's worth noting.
Upvotes: 1