I have a directive that builds a set of nested <ul> elements representing the folder structure. I used the link function to create new DOM elements and added them to the instance element of the directive:
function link(scope, iElement, iAttr) { var rootElement = buildChildElement(scope.tree); iElement.append(rootElement); }
Elements in the <ul> tree are connected using jQueryUI drag / drop interactions that invoke a function on the controller that contains the directive to update the area parameter based on drag and drop events.
I would like the <ul> tree to automatically update when the area parameter changes. I tried the clock function in my link function:
scope.$watch('tree', function(newTree, oldTree) { var newRoot = buildChildElement(newTree); iElement.contents().remove(); iElement.append(newRoot); }
This works to a degree, but the remove() call launches the $watch() method a second time, which ultimately returns my changes to the controller. If I comment on remove() , I see that a new <ul> tree has been written that correctly reflects the changes to the parameter introduced into the controller.
The double shooting of $watch() makes me think that I'm going to do it wrong. Without it, my parameter is updated correctly, but my <ul> not updated (the dropped item remains where it was deleted).
What is the right way to make sure your directive is updated when you change one of the scope parameters?
Should I use the compile function and build the <ul> tree based on an array of attributes instead of using the link function?
source share