1

I am new to Angular and would like to simply move an element when it is clicked to another div. How is the best way to do this?

<div ng-app>
    <h1>First area</h1>
    <ul>
        <li ng-repeat="elem in elems">
            {{ elem.elem_name }}
        </li>
    </ul>
    <h1>Second Area</h1>
    <ul>
        <li>

        </li>
    </ul>
</div>

So given the example in my JS file how would I make it so when I click an elem it leaves the first area and appears in the second area?

2 Answers 2

2

Add a selected property to each item and toggle it when it's clicked. Use a filter to filter each list based on selected...

$scope.items = [{name: "foo", selected: false},
                {name: "bar", selected: false},
                {name: "baz", selected: false},
                {name: "quux", selected: false}];

$scope.move = function(item) {
    item.selected = !item.selected;
};

View

List 1
<ul>
  <li ng-repeat="item in items | filter : {selected: false}">
    {{ item.name }}
    <a href="#" ng-click="move(item)">move</a>
  </li>
</ul>

List 2
<ul>
  <li ng-repeat="item in items | filter : {selected: true}">
    {{ item.name }}
    <a href="#" ng-click="move(item)">move</a>
  </li>
</ul>

JsBin: http://jsbin.com/sawotuza/1/edit?html,js,output

Sign up to request clarification or add additional context in comments.

Comments

2

I know little about Angular.js but I'd be surprised if the way to do this did not involve adding a new set of elements just for the "Second area" like so:

<h1>Second Area</h1>
<ul>
     <li ng-repeat="elem in secondElems">
         {{ elem.elem_name }}
     </li>
</ul>

And then programatically removing the clicked element from elems and putting it in secondElems.

2 Comments

When moving a DOM element, there is no need to remove it first, assigning it to the new location automatically removes it from its current location, e.g. insertBefore: If the newChild is already in the tree, it is first removed.
What urig described is a correct way of dealing with this in Angular, where you're moving items from one array to another. There is no direct DOM manipulation, databinding takes care of that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.