Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move a view around the DOM with angular.js?

How can I move an element to different places in the DOM with angular js?

I have a list of elements like so

<ul id="list" ng-controller="ListController">
    <li ng-controller="ItemController"><div>content</div></li>
    <li ng-controller="ItemController"><div>content</div></li>
    <li ng-controller="ItemController"><div>content</div></li>
    <li ng-controller="ItemController">
        <div>content</div>
        <div id="overlay"></div>
    </li>
</ul>

What I'm trying to accomplish is moving the #overlay from place to place within the list without having to have a hidden duplicate in every item that I flag hidden/unhidden.

If this was jquery I could just do something like this:

$("#overlay").appendTo("#list li:first-child");

Is there an equivalent way to do this in angular?

like image 879
bitwit Avatar asked Dec 07 '22 12:12

bitwit


1 Answers

Thanks to your clarifications I can understand that you've got a list of items. You would like to be able to select one item in this list (swipe but potentially other events as well) and then display an additional DOM element (div) for a selected item. If the other item was selected it should be un-selected - this way only one item should have an additional div displayed.

If the above understanding is correct, then you could solve this with the simple ng-repeat and ng-show directives like this:

<ul ng-controller="ListController">
    <li ng-repeat="item in items">
        <div ng-click="open(item)">{{item.content}}</div>
        <div ng-show="isOpen(item)">overlay: tweet, share, pin</div>
    </li>
</ul>

where the code in the controller would be (showing a fragment of it only):

$scope.open = function(item){
    if ($scope.isOpen(item)){
        $scope.opened = undefined;
    } else {
        $scope.opened = item;
    }        
};

$scope.isOpen = function(item){
    return $scope.opened === item;
};

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/65Cxv/7/

If you are concerned about having too many DOM elements you could achieve the same using ng-switch directive:

<ul ng-controller="ListController">
    <li ng-repeat="item in items">
        <div ng-click="open(item)">{{item.content}}</div>
        <ng-switch on="isOpen(item)">
            <div ng-switch-when="true">overlay: tweet, share, pin</div>
        </ng-switch>        
    </li>
</ul>

Here is the jsFiddle: http://jsfiddle.net/pkozlowski_opensource/bBtH3/2/

like image 75
pkozlowski.opensource Avatar answered Dec 30 '22 05:12

pkozlowski.opensource