Change DOM element location in AngularJS

I currently have an angular directive that works similarly to a carousel. To preserve the value of the dom element, I remove the elements from the dom and re-insert them. I currently use angular.element

to select, delete and insert new items like this:

app.directive('myDirective', function(){
    return{
        link: function(scope, elem){
            var jqLite = angular.element;

            var parentElement = jqLite(elem[0].queryselector('.parent'));

            // Selection..
            var oldElement = jqLite(elem[0].queryselector('.oldItem'));
            var newElement = jqLite('<div class=".newItem">Content here</div>');

            oldElement.remove();

            parentElement.append(newElement);

        }
    }
});

      

Basically this code finds oldElement

and removes it and creates newElement

and adds it to the parent of the container. Basically I want to know if it is possible to move it oldElement

to a new location rather than deleting and creating an entire new item?

+3


source to share


1 answer


This is how append (Node.prototype.appendChild) works . It moves the element to a new location if it is already in the DOM tree, or creates a new element and inserts into the DOM if it doesn't already exist.

In your case:

app.directive('myDirective', function(){
    return{
        link: function(scope, elem) {
            var jqLite = angular.element;

            var parentElement = jqLite(elem[0].querySelector('.parent'));
            var oldElement = jqLite(elem[0].querySelector('.oldItem'));

            parentElement.append(oldElement);
        }
    }
});

      



or rather, because you don't need jQuery / jqLite) for such a simple DOM trick:

link: function(scope, elem){
    var parentElement = elem[0].querySelector('.parent');
    var oldElement = elem[0].querySelector('.oldItem');
    parentElement.appendChild(oldElement);
}

      

+4


source







All Articles