AngularJS directive - function to re-launch a link to change a parameter of a region

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?

+4
source share
2 answers

Your approach is very jQuery-style. I think you will find that in this case you are working against Angular. sh0ber is right with his question; you should post a demo or something else, or at least a sample code so you can get an effective answer.

I think you want to create a recursive tree directive. See this "SO" answer for some interesting approaches to this. The basic idea is that a watch is not needed. Just change the object, and Angular will take care of the rest. The most effective is to modify specific node objects directly, rather than replacing the entire object, but this will work too.

0
source
 scope.$watch('tree', function(newTree, oldTree) { var newRoot = buildChildElement(newTree); iElement.contents().remove(); iElement.append(newRoot); },**true**) 

I think you can try and refer to the clock API for more information. Here is another artistic http://www.bennadel.com/blog/2566-scope-watch-vs-watchcollection-in-angularjs.htm

0
source

Source: https://habr.com/ru/post/1483799/


All Articles